<commit_before>'use strict';

var Promise = global.Promise || require('promise');

var glob       = require('glob'),
    Handlebars = require('handlebars'),
    fs         = require('graceful-fs'),
    path       = require('path'),
    semver     = require('semver'),
    utils      = require('./utils');

module.exports = ExpressHandlebars;

// -----------------------------------------------------------------------------

function ExpressHandlebars(config) {
    config || (config = {});

    this.handlebars  = config.handlebars  || this.handlebars;
    this.extname     = config.extname     || this.extname;
    this.layoutsDir  = config.layoutsDir  || this.layoutsDir;
    this.partialsDir = config.partialsDir || this.partialsDir;

    this.handlebarsVersion =
            ExpressHandlebars.getHandlebarsSemver(this.handlebars);

    if (this.extname.charAt(0) !== '.') {
        this.extname = '.' + this.extname;
    }

    this.defaultLayout = config.defaultLayout;
    this.helpers       = config.helpers;

    this.compiled    = {};
    this.precompiled = {};

    this.engine = this.renderView.bind(this);
}

ExpressHandlebars._fsCache = {};

ExpressHandlebars.getHandlebarsSemver = function (handlebars) {
    var version = handlebars.VERSION || '';

    // Makes sure the Handlebars version is a valid semver.
    if (version && !semver.valid(version)) {
        version = version.replace(/(\d\.\d)\.(\D.*)/, '$1.0-$2');
    }

    return version;
};

ExpressHandlebars.prototype.handlebars  = Handlebars;
ExpressHandlebars.prototype.extname     = '.handlebars';
ExpressHandlebars.prototype.layoutsDir  = 'views/layouts/';
ExpressHandlebars.prototype.partialsDir = 'views/partials/';

ExpressHandlebars.prototype.compileTemplate = function (template, options) {
    options || (options = {});

    var compiler = options.precompiled ? 'precompile' : 'compile',
        compile  = this.handlebars[compiler];

    return compile(template);
};

ExpressHandlebars.prototype.getPartials = function (options) {
    options || (options = {});

    var partialsDirs = Array.isArray(this.partialsDir) ?
            this.partialsDir : [this.partialsDir];

    partialsDirs = partialsDirs.map(function (dir) {
        var namespace;

        // Support `partialsDir` collection with object entries that contain a
        // namespace.
        if (dir && typeof dir !== 'string') {
            namespace = dir.namespace;
            dir       = dir.dir;
        }

        return this.getTemplates(dir, options).then(function (templates) {
            return {
                templates: templates,
                namespace: namespace
            };
        });
    }, this);

    return Promise.all(partialsDirs).then(function (dirs) {
        var getPartialName = this._getPartialName.bind(this);

        return dirs.reduce(function (partials, dir) {
            var templates = dir.templates,
                namespace = dir.namespace,
                filePaths = Object.keys(templates);

            filePaths.forEach(function (filePath) {
                var partialName = getPartialName(filePath, namespace);
                partials[partialName] = templates[filePath];
            });

            return partials;
        }, {});
    }.bind(this));
};

ExpressHandlebars.prototype.getTemplate = function (filePath, options) {
    filePath = path.resolve(filePath);
    options || (options = {});

    var precompiled = options.precompiled,
        cache       = precompiled ? this.precompiled : this.compiled,
        template    = options.cache && cache[filePath];

    if (template) {
        return template;
    }

    // Optimistically cache template promise to reduce file system I/O, but
    // remove from cache if there was a problem.
    template = cache[filePath] = this._getFile(filePath, options)
        .then(function (file) {
            return this.compileTemplate(file, options);
        }.bind(this));

    return template.catch(function (err) {
        delete cache[filePath];
        throw err;
    });
};

ExpressHandlebars.prototype.getTemplates = function (dirPath, options) {
    options || (options = {});

    return this._getDir(dirPath, options).then(function (filePaths) {
        var templates = filePaths.map(function (filePath) {
            return this.getTemplate(path.join(dirPath, filePath), options);
        }, this);

        return Promise.all(templates).then(function (templates) {
            return filePaths.reduce(function (map, filePath, i) {
                map[filePath] = templates[i];
                return map;
            }, {});
        });
    }.bind(this));
};

ExpressHandlebars.prototype.render = function (filePath, context, options) {
    options || (options = {});

    // Force `precompiled` to `false` since we're rendering to HTML.
    if (options.precompiled) {
        options = utils.extend({}, options, {precompiled: false});
    }

    return Promise.all([
        this.getTemplate(filePath, options),
        options.partials || this.getPartials(options)
    ]).then(function (templates) {
        var template = templates[0],
            partials = templates[1],
            data     = options.data;

        var helpers = options.helpers ||
                utils.extend({}, this.handlebars.helpers, this.helpers);

        return this._renderTemplate(template, context, {
            data    : data,
            helpers : helpers,
            partials: partials
        });
    }.bind(this));
};

ExpressHandlebars.prototype.renderView = function (viewPath, options, callback) {
    var context = options,
        data    = options.data;

    var helpers = utils.extend({},
            this.handlebars.helpers, this.helpers, options.helpers);

    // Pluck-out ExpressHandlebars-specific options.
    options = {
        cache      : options.cache,
        layout     : 'layout' in options ? options.layout : this.defaultLayout,
        precompiled: false
    };

    // Extend `options` with Handlebars-specific rendering options.
    utils.extend(options, {
        data    : data,
        helpers : helpers,
        partials: this.getPartials(options)
    });

    this.render(viewPath, context, options)
        .then(function (body) {
            var layoutPath = this._resolveLayoutPath(options.layout);

            if (layoutPath) {
                context = utils.extend({}, context, {body: body});
                return this.render(layoutPath, context, options);
            }

            return body;
        }.bind(this))
        .then(utils.passValue(callback))
        .catch(utils.passError(callback));
};

ExpressHandlebars.prototype._getDir = function (dirPath, options) {
    dirPath = path.resolve(dirPath);

    var cache = ExpressHandlebars._fsCache,
        dir   = options.cache && cache[dirPath];

    if (dir) {
        return dir.then(function (dir) {
            return dir.concat();
        });
    }

    var pattern = '**/*' + this.extname;

    // Optimistically cache dir promise to reduce file system I/O, but remove
    // from cache if there was a problem.
    dir = cache[dirPath] = new Promise(function (resolve, reject) {
        glob(pattern, {cwd: dirPath}, function (err, dir) {
            if (err) {
                reject(err);
            } else {
                resolve(dir);
            }
        });
    });

    return dir.then(function (dir) {
        return dir.concat();
    }).catch(function (err) {
        delete cache[dirPath];
        throw err;
    });
};

ExpressHandlebars.prototype._getFile = function (filePath, options) {
    filePath = path.resolve(filePath);

    var cache = ExpressHandlebars._fsCache,
        file  = options.cache && cache[filePath];

    if (file) {
        return file;
    }

    // Optimistically cache file promise to reduce file system I/O, but remove
    // from cache if there was a problem.
    file = cache[filePath] = new Promise(function (resolve, reject) {
        fs.readFile(filePath, 'utf8', function (err, file) {
            if (err) {
                reject(err);
            } else {
                resolve(file);
            }
        });
    });

    return file.catch(function (err) {
        delete cache[filePath];
        throw err;
    });
};

ExpressHandlebars.prototype._getPartialName = function (filePath, namespace) {
    var extRegex = new RegExp(this.extname + '$'),
        name     = filePath.replace(extRegex, ''),
        version  = this.handlebarsVersion;

    if (namespace) {
        name = namespace + '/' + name;
    }

    // Fixes a Handlebars bug in versions prior to 1.0.rc.2 which caused
    // partials with "/"s in their name to not be found.
    // https://github.com/wycats/handlebars.js/pull/389
    if (version && !semver.satisfies(version, '>=1.0.0-rc.2')) {
        name = name.replace(/\//g, '.');
    }

    return name;
};

ExpressHandlebars.prototype._renderTemplate = function (template, context, options) {
    return template(context, options);
};

ExpressHandlebars.prototype._resolveLayoutPath = function (layoutPath) {
    if (!layoutPath) {
        return null;
    }

    if (!path.extname(layoutPath)) {
        layoutPath += this.extname;
    }

    if (layoutPath.charAt(0) !== '/') {
        layoutPath = path.join(this.layoutsDir, layoutPath);
    }

    return layoutPath;
};
<commit_msg>Allow each partials dir to be configured<commit_after>'use strict';

var Promise = global.Promise || require('promise');

var glob       = require('glob'),
    Handlebars = require('handlebars'),
    fs         = require('graceful-fs'),
    path       = require('path'),
    semver     = require('semver'),
    utils      = require('./utils');

module.exports = ExpressHandlebars;

// -----------------------------------------------------------------------------

function ExpressHandlebars(config) {
    config || (config = {});

    this.handlebars  = config.handlebars  || this.handlebars;
    this.extname     = config.extname     || this.extname;
    this.layoutsDir  = config.layoutsDir  || this.layoutsDir;
    this.partialsDir = config.partialsDir || this.partialsDir;

    this.handlebarsVersion =
            ExpressHandlebars.getHandlebarsSemver(this.handlebars);

    if (this.extname.charAt(0) !== '.') {
        this.extname = '.' + this.extname;
    }

    this.defaultLayout = config.defaultLayout;
    this.helpers       = config.helpers;

    this.compiled    = {};
    this.precompiled = {};

    this.engine = this.renderView.bind(this);
}

ExpressHandlebars._fsCache = {};

ExpressHandlebars.getHandlebarsSemver = function (handlebars) {
    var version = handlebars.VERSION || '';

    // Makes sure the Handlebars version is a valid semver.
    if (version && !semver.valid(version)) {
        version = version.replace(/(\d\.\d)\.(\D.*)/, '$1.0-$2');
    }

    return version;
};

ExpressHandlebars.prototype.handlebars  = Handlebars;
ExpressHandlebars.prototype.extname     = '.handlebars';
ExpressHandlebars.prototype.layoutsDir  = 'views/layouts/';
ExpressHandlebars.prototype.partialsDir = 'views/partials/';

ExpressHandlebars.prototype.compileTemplate = function (template, options) {
    options || (options = {});

    var compiler = options.precompiled ? 'precompile' : 'compile',
        compile  = this.handlebars[compiler];

    return compile(template);
};

ExpressHandlebars.prototype.getPartials = function (options) {
    options || (options = {});

    var partialsDirs = Array.isArray(this.partialsDir) ?
            this.partialsDir : [this.partialsDir];

    partialsDirs = partialsDirs.map(function (dir) {
        var dirOptions = options;

        // Support `partialsDir` collection with object entries that contain a
        // namespace.
        if (dir && typeof dir !== 'string') {
            dirOptions = utils.extend({}, options, dir);
            dir        = dir.dir;
        }

        return this.getTemplates(dir, dirOptions).then(function (templates) {
            return {
                templates: templates,
                namespace: dirOptions.namespace
            };
        });
    }, this);

    return Promise.all(partialsDirs).then(function (dirs) {
        var getPartialName = this._getPartialName.bind(this);

        return dirs.reduce(function (partials, dir) {
            var templates = dir.templates,
                namespace = dir.namespace,
                filePaths = Object.keys(templates);

            filePaths.forEach(function (filePath) {
                var partialName = getPartialName(filePath, namespace);
                partials[partialName] = templates[filePath];
            });

            return partials;
        }, {});
    }.bind(this));
};

ExpressHandlebars.prototype.getTemplate = function (filePath, options) {
    filePath = path.resolve(filePath);
    options || (options = {});

    var precompiled = options.precompiled,
        cache       = precompiled ? this.precompiled : this.compiled,
        template    = options.cache && cache[filePath];

    if (template) {
        return template;
    }

    // Optimistically cache template promise to reduce file system I/O, but
    // remove from cache if there was a problem.
    template = cache[filePath] = this._getFile(filePath, options)
        .then(function (file) {
            return this.compileTemplate(file, options);
        }.bind(this));

    return template.catch(function (err) {
        delete cache[filePath];
        throw err;
    });
};

ExpressHandlebars.prototype.getTemplates = function (dirPath, options) {
    options || (options = {});

    return this._getDir(dirPath, options).then(function (filePaths) {
        var templates = filePaths.map(function (filePath) {
            return this.getTemplate(path.join(dirPath, filePath), options);
        }, this);

        return Promise.all(templates).then(function (templates) {
            return filePaths.reduce(function (map, filePath, i) {
                map[filePath] = templates[i];
                return map;
            }, {});
        });
    }.bind(this));
};

ExpressHandlebars.prototype.render = function (filePath, context, options) {
    options || (options = {});

    // Force `precompiled` to `false` since we're rendering to HTML.
    if (options.precompiled) {
        options = utils.extend({}, options, {precompiled: false});
    }

    return Promise.all([
        this.getTemplate(filePath, options),
        options.partials || this.getPartials(options)
    ]).then(function (templates) {
        var template = templates[0],
            partials = templates[1],
            data     = options.data;

        var helpers = options.helpers ||
                utils.extend({}, this.handlebars.helpers, this.helpers);

        return this._renderTemplate(template, context, {
            data    : data,
            helpers : helpers,
            partials: partials
        });
    }.bind(this));
};

ExpressHandlebars.prototype.renderView = function (viewPath, options, callback) {
    var context = options,
        data    = options.data;

    var helpers = utils.extend({},
            this.handlebars.helpers, this.helpers, options.helpers);

    // Pluck-out ExpressHandlebars-specific options.
    options = {
        cache      : options.cache,
        layout     : 'layout' in options ? options.layout : this.defaultLayout,
        precompiled: false
    };

    // Extend `options` with Handlebars-specific rendering options.
    utils.extend(options, {
        data    : data,
        helpers : helpers,
        partials: this.getPartials(options)
    });

    this.render(viewPath, context, options)
        .then(function (body) {
            var layoutPath = this._resolveLayoutPath(options.layout);

            if (layoutPath) {
                context = utils.extend({}, context, {body: body});
                return this.render(layoutPath, context, options);
            }

            return body;
        }.bind(this))
        .then(utils.passValue(callback))
        .catch(utils.passError(callback));
};

ExpressHandlebars.prototype._getDir = function (dirPath, options) {
    dirPath = path.resolve(dirPath);

    var cache = ExpressHandlebars._fsCache,
        dir   = options.cache && cache[dirPath];

    if (dir) {
        return dir.then(function (dir) {
            return dir.concat();
        });
    }

    var pattern = '**/*' + this.extname;

    // Optimistically cache dir promise to reduce file system I/O, but remove
    // from cache if there was a problem.
    dir = cache[dirPath] = new Promise(function (resolve, reject) {
        glob(pattern, {cwd: dirPath}, function (err, dir) {
            if (err) {
                reject(err);
            } else {
                resolve(dir);
            }
        });
    });

    return dir.then(function (dir) {
        return dir.concat();
    }).catch(function (err) {
        delete cache[dirPath];
        throw err;
    });
};

ExpressHandlebars.prototype._getFile = function (filePath, options) {
    filePath = path.resolve(filePath);

    var cache = ExpressHandlebars._fsCache,
        file  = options.cache && cache[filePath];

    if (file) {
        return file;
    }

    // Optimistically cache file promise to reduce file system I/O, but remove
    // from cache if there was a problem.
    file = cache[filePath] = new Promise(function (resolve, reject) {
        fs.readFile(filePath, 'utf8', function (err, file) {
            if (err) {
                reject(err);
            } else {
                resolve(file);
            }
        });
    });

    return file.catch(function (err) {
        delete cache[filePath];
        throw err;
    });
};

ExpressHandlebars.prototype._getPartialName = function (filePath, namespace) {
    var extRegex = new RegExp(this.extname + '$'),
        name     = filePath.replace(extRegex, ''),
        version  = this.handlebarsVersion;

    if (namespace) {
        name = namespace + '/' + name;
    }

    // Fixes a Handlebars bug in versions prior to 1.0.rc.2 which caused
    // partials with "/"s in their name to not be found.
    // https://github.com/wycats/handlebars.js/pull/389
    if (version && !semver.satisfies(version, '>=1.0.0-rc.2')) {
        name = name.replace(/\//g, '.');
    }

    return name;
};

ExpressHandlebars.prototype._renderTemplate = function (template, context, options) {
    return template(context, options);
};

ExpressHandlebars.prototype._resolveLayoutPath = function (layoutPath) {
    if (!layoutPath) {
        return null;
    }

    if (!path.extname(layoutPath)) {
        layoutPath += this.extname;
    }

    if (layoutPath.charAt(0) !== '/') {
        layoutPath = path.join(this.layoutsDir, layoutPath);
    }

    return layoutPath;
};
<|endoftext|>


<commit_before>let nextId = 0;
let cellTemplateGenerators = {
    artifactoryRepoPathColumn: function(specialClass) {
        return '
{{row.entity.repoKey}}/{{row.entity.path}}
' +
            '
{{row.entity.path}}
';
    },

    downloadableColumn: function(specialClass) {
        return '

{{row.entity.name}}
' +
            '
{{row.entity.name}}

';
    },

    booleanColumn: function(model) {
        return '
<input ng-model="' +
            model + '" type="checkbox" disabled/>
';
    },
    checkboxColumn: function(model, click, disabled) {
        return '

<jf-checkbox><input ng-model="' + model + '"' +
            (click && click.length ? ' ng-click="' + click + '"' : '') +
            (disabled && disabled.length ? ' ng-disabled="' + disabled + '"' : '') +
            ' type="checkbox"/></jf-checkbox>

';
    },
    listableColumn: function(listModel,rowNameModel,displayModel,alwaysShow,testIdPrefix=null,showAsyncData, externalCountModel) {

        testIdPrefix = testIdPrefix ? testIdPrefix + '-' : '';

        displayModel = displayModel ? `{{${listModel}.length}} | {{${displayModel}}}` : `{{${externalCountModel} ? ${externalCountModel} : ${listModel}.length}} | {{${listModel}.join(\', \')}}{{${externalCountModel} && ${externalCountModel} > ${listModel}.length ? ',...' : ''}}`;

        let id = `${testIdPrefix}{{row.uid}}_${nextId}`;

        let template =  `

                                ${displayModel}
                                  (See All)
                                  (See All)

-

`;

        nextId++;
        return template;
    },
    iconColumn: function(cellText, cellIcon, iconClass) {
        return '
{{' + cellText + '}}
';
    },
    ajaxColumn: function () {
        return '

{{row.entity.status}}
';
    }
}

export default cellTemplateGenerators;<commit_msg>jf-table-view: Fixes and improvement (mainly to support special cellTemplates)<commit_after>let nextId = 0;
let cellTemplateGenerators = {
    artifactoryRepoPathColumn: function(specialClass) {
        return '
{{row.entity.repoKey}}/{{row.entity.path}}
' +
            '
{{row.entity.path}}
';
    },

    downloadableColumn: function(specialClass) {
        return '

{{row.entity.name}}
' +
            '
{{row.entity.name}}

';
    },

    booleanColumn: function(model) {
        return '
<input ng-model="' +
            model + '" type="checkbox" disabled/>
';
    },
    checkboxColumn: function(model, click, disabled) {
        return '

<jf-checkbox><input ng-model="' + model + '"' +
            (click && click.length ? ' ng-click="' + click + '"' : '') +
            (disabled && disabled.length ? ' ng-disabled="' + disabled + '"' : '') +
            ' type="checkbox"/></jf-checkbox>

';
    },
    listableColumn: function(listModel,rowNameModel,displayModel,alwaysShow,testIdPrefix=null,showAsyncData, externalCountModel) {

        testIdPrefix = testIdPrefix ? testIdPrefix + '-' : '';

        displayModel = displayModel ? `{{${listModel}.length}} | {{${displayModel}}}` : `{{${externalCountModel} ? ${externalCountModel} : ${listModel}.length}} | {{${listModel}.join(\', \')}}{{${externalCountModel} && ${externalCountModel} > ${listModel}.length ? ',...' : ''}}`;

        let id = `${testIdPrefix}{{row.uid}}_${nextId}`;

        let template =  `

                                ${displayModel}
                                  (See All)
                                  (See All)

-

`;

        nextId++;
        return template;
    },
    iconColumn: function(cellText, cellIcon, iconClass) {
        return '
{{' + cellText + '}}
';
    },
    ajaxColumn: function () {
        return '

{{row.entity.status}}
';
    }
}

export default cellTemplateGenerators;<|endoftext|>


<commit_before>import { reduxForm } from 'redux-form'

import CheckInForm from '../components/CheckInForm'
import { updateInfo, clearInfo } from '../modules/check-in'

const fields = [
  'firstName',
  'lastName',
  'socialSecurityNumber',
  'dateOfBirth',
  'phoneNumber',
  'emailAddress',

  'gender',
  'isTransexual',
  'isLGBTQ',

  'ethnicity',
  'ethnicityOther',

  'language',
  'languageOther',

  'hasBeenInFosterCare',

  'hasServedInTheMilitary',

  'primaryHealthcareLocation',

  'isHomeless',
  'lengthOfHomelessness',

  'medicalServices',
  'supportServices',
]

const validate = (values) => {
  const errors = {}
  // if (!values.firstName) {
  //   errors.firstName = 'Required'
  // }
  //
  // if (!values.lastName) {
  //   errors.lastName = 'Required'
  // }
  //
  // if (!values.dateOfBirth) {
  //   errors.dateOfBirth = 'Required'
  // }

  return errors
}

const mapStateToProps = (state) => ({
  initialValues: state.checkIn.primaryInfo,
})

const mapDispatchToProps = (dispatch) => ({
  updateInfo: (fields) => dispatch(updateInfo(fields)),
  clearInfo: () => dispatch(clearInfo()),
})

export default reduxForm({
  form: 'checkIn',
  fields,
  validate,
},
mapStateToProps,
mapDispatchToProps
)(CheckInForm)
<commit_msg>use new normalizers for some validation<commit_after>import { reduxForm } from 'redux-form'

import CheckInForm from '../components/CheckInForm'
import { updateInfo, clearInfo } from '../modules/check-in'

const fields = [
  'firstName',
  'lastName',
  'socialSecurityNumber',
  'dateOfBirth',
  'phoneNumber',
  'emailAddress',

  'gender',
  'isTransexual',
  'isLGBTQ',

  'ethnicity',
  'ethnicityOther',

  'language',
  'languageOther',

  'hasBeenInFosterCare',

  'hasServedInTheMilitary',

  'primaryHealthcareLocation',

  'isHomeless',
  'lengthOfHomelessness',

  'medicalServices',
  'supportServices',
]

const validate = (values) => {
  const errors = {}
  if (!values.firstName) {
    errors.firstName = 'Required'
  }

  if (!values.lastName) {
    errors.lastName = 'Required'
  }

  if (!values.socialSecurityNumber) {
    errors.socialSecurityNumber = 'Required'
  } else if (values.socialSecurityNumber.length < 11) {
    errors.socialSecurityNumber = 'Incomplete'
  }

  if (!values.phoneNumber) {
    errors.phoneNumber = 'Required'
  } else if (values.phoneNumber.length < 14) {
    errors.phoneNumber = 'Incomplete'
  }

  return errors
}

const mapStateToProps = (state) => ({
  initialValues: state.checkIn.primaryInfo,
})

const mapDispatchToProps = (dispatch) => ({
  updateInfo: (fields) => dispatch(updateInfo(fields)),
  clearInfo: () => dispatch(clearInfo()),
})

export default reduxForm({
  form: 'checkIn',
  fields,
  validate,
},
mapStateToProps,
mapDispatchToProps
)(CheckInForm)
<|endoftext|>


<commit_before>/*
 *     Copyright (c) 2011-2015 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/* global StyledElements */

(function (se, utils) {

    "use strict";

    // ==================================================================================
    // CLASS DEFINITION
    // ==================================================================================

    se.Container = utils.defineClass({

        /**
         * Create a new instance of class Container.
         *
         * @constructor
         * @extends StyledElements.StyledElement
         * @name StyledElements.Container
         * @since 0.5
         * @param {Object.<String, *>} options [description]
         * @param {String[]} events [description]
         */
        constructor: function Container(options, events) {
            options = utils.merge(utils.clone(defaults), options);
            this.superClass(events);

            this.wrapperElement = document.createElement(options.tagname);
            this.wrapperElement.className = 'se-container';
            this.children = [];
            this.useFullHeight = options.useFullHeight;

            if (options.id) {
                this.wrapperElement.setAttribute('id', options.id);
            }

            this.addClassName(options['class']);
            this.addClassName(options.extraClass);
        },

        inherit: se.StyledElement,

        members: /** @lends StyledElements.Container.prototype */ {

            /**
             * Check if an element is a descendant of the wrapperElement.
             * @since 0.6
             *
             * @param {StyledElements.StyledElement|HTMLElement} childElement
             *      An element that may be contained.
             * @returns {Boolean}
             *      If the given element is a descendant of the wrapperElement, even so
             *      it is a direct child or nested more deeply.
             */
            has: function has(childElement) {

                if (childElement instanceof se.StyledElement && this.children.indexOf(childElement) !== -1) {
                    return true;
                }

                return childElement.parentElement == this.get();
            },

            /**
             */
            remove: function remove(childElement) {
                var index;

                if (childElement == null) {
                    return this.superMember(se.StyledElement, 'remove', childElement);
                }

                if (childElement instanceof se.StyledElement) {
                    if ((index = this.children.indexOf(childElement)) === -1) {
                        return this;
                    }

                    this.children.splice(index, 1);
                    childElement.parentElement = null;

                    // Get the DOM element
                    childElement = childElement.get();
                }

                if (childElement.parentElement === this.get()) {
                    this.get().removeChild(childElement);
                }

                return this;
            },

            /**
             * Insert an element at the end of this container or before the
             * refElement if provided.
             *
             * @since 0.5
             * @param {StyledElements.StyledElement|HTMLElement|String} newElement
             *      An element to insert into the wrapperElement.
             * @param {StyledElements.StyledElement|HTMLElement} [refElement]
             *      Optional. An element after which newElement is inserted.
             * @returns {StyledElements.Container}
             *      The instance on which the member is called.
             */
            appendChild: function appendChild(element, refElement) {
                if (element instanceof StyledElements.StyledElement) {
                    element.insertInto(this.wrapperElement, refElement);
                    element.parentElement = this;
                    this.children.push(element);

                    return this;
                }

                if (typeof element === "string") {
                    element = document.createTextNode(element);
                }

                if (refElement instanceof StyledElements.StyledElement) {
                    refElement = refElement.get();
                }

                if (refElement != null) {
                    this.wrapperElement.insertBefore(element, refElement);
                } else {
                    this.wrapperElement.appendChild(element);
                }

                return this;
            },

            /**
             * Inserts a new element to the beginning of this Container
             * @since 0.6
             *
             * @param {StyledElement|HTMLElement|String} newElement
             *      An element to insert into the wrapperElement.
             * @param {StyledElement|HTMLElement} [refElement]
             *      Optional. An element before which newElement is inserted.
             * @returns {StyledElement}
             *      The instance on which the member is called.
             */
            prependChild: function prependChild(newElement, refElement) {
                return this.appendChild(newElement, this.get().firstChild);
            },

            removeChild: function removeChild(element) {
                if (element == null) {
                    throw new TypeError('missing element parameter');
                }

                return this.remove(element);
            },

            repaint: function repaint(temporal) {
                temporal = temporal !== undefined ? temporal : false;

                if (this.useFullHeight) {
                    if (this.wrapperElement.classList.contains('hidden')) {
                        this.wrapperElement.style.height = "";
                        return;
                    }

                    var height = this._getUsableHeight();
                    if (height == null) {
                        return; // nothing to do
                    }

                    this.wrapperElement.style.height = (height + "px");
                }

                for (var i = 0; i < this.children.length; i++) {
                    this.children[i].repaint(temporal);
                }

                if (this.disabledLayer != null) {
                    this.disabledLayer.style.height = this.wrapperElement.scrollHeight + 'px';
                    this.disabledLayer.style.lineHeight = this.wrapperElement.clientHeight + 'px';
                }
            },

            clear: function clear() {
                this.children = [];
                this.wrapperElement.innerHTML = "";
                this.wrapperElement.scrollTop = 0;
                this.wrapperElement.scrollLeft = 0;
                if (this.disabledLayer != null) {
                    this.wrapperElement.appendChild(this.disabledLayer);
                }

                return this;
            },

            text: function (text) {
                if (text == null) {
                    return this.get().textContent;
                }

                this.children = [];
                this.wrapperElement.textContent = "" + text;
            },

            /**
             * @deprecated since version 0.6.0
             */
            isDisabled: function isDisabled() {
                return this.disabledLayer != null;
            },

            _onenabled: function _onenabled(enabled) {
                if (enabled) {
                    this.disabledLayer.parentNode.removeChild(this.disabledLayer);
                    this.disabledLayer = null;
                    this.disable_icon = null;
                } else {
                    this.disabledLayer = document.createElement('div');
                    this.disabledLayer.className = 'se-container-disable-layer';

                    this.disabled_icon = document.createElement('i');
                    this.disabled_icon.className = 'disable-icon icon-spin icon-spinner';
                    this.disabledLayer.appendChild(this.disabled_icon);

                    this.wrapperElement.appendChild(this.disabledLayer);
                    this.disabledLayer.style.height = this.wrapperElement.scrollHeight + 'px';
                    this.disabledLayer.style.lineHeight = this.wrapperElement.clientHeight + 'px';
                }
            }
        }

    });

    // ==================================================================================
    // PRIVATE MEMBERS
    // ==================================================================================

    var defaults = {
        'class': "",
        id: "",
        extraClass: "",
        tagname: 'div',
        useFullHeight: false
    };

})(StyledElements, StyledElements.Utils);
<commit_msg>Refactor Container to use se helpers<commit_after>/*
 *     Copyright (c) 2011-2015 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/* global StyledElements */

(function (se, utils) {

    "use strict";

    // ==================================================================================
    // CLASS DEFINITION
    // ==================================================================================

    se.Container = utils.defineClass({

        /**
         * Create a new instance of class Container.
         *
         * @constructor
         * @extends StyledElements.StyledElement
         * @name StyledElements.Container
         * @since 0.5
         * @param {Object.<String, *>} options [description]
         * @param {String[]} events [description]
         */
        constructor: function Container(options, events) {
            options = utils.merge(utils.clone(defaults), options);
            this.superClass(events);

            this.wrapperElement = document.createElement(options.tagname);
            this.wrapperElement.className = 'se-container';
            this.children = [];
            this.useFullHeight = options.useFullHeight;

            if (options.id) {
                this.wrapperElement.setAttribute('id', options.id);
            }

            this.addClassName(options['class']);
            this.addClassName(options.extraClass);
        },

        inherit: se.StyledElement,

        members: /** @lends StyledElements.Container.prototype */ {

            /**
             * Check if an element is a descendant of the wrapperElement.
             * @since 0.6
             *
             * @param {StyledElements.StyledElement|HTMLElement} childElement
             *      An element that may be contained.
             * @returns {Boolean}
             *      If the given element is a descendant of the wrapperElement, even so
             *      it is a direct child or nested more deeply.
             */
            has: function has(childElement) {

                if (childElement instanceof se.StyledElement && this.children.indexOf(childElement) !== -1) {
                    return true;
                }

                return childElement.parentElement == this.get();
            },

            /**
             */
            remove: function remove(childElement) {
                var index;

                if (childElement == null) {
                    return this.superMember(se.StyledElement, 'remove', childElement);
                }

                if (childElement instanceof se.StyledElement) {
                    if ((index = this.children.indexOf(childElement)) === -1) {
                        return this;
                    }

                    this.children.splice(index, 1);
                    childElement.parentElement = null;

                    // Get the DOM element
                    childElement = childElement.get();
                }

                if (childElement.parentElement === this.get()) {
                    this.get().removeChild(childElement);
                }

                return this;
            },

            /**
             * Insert the `newElement` either to the end of this Container
             * or after the `refElement` given.
             * @since 0.5
             *
             * @param {(StyledElements.StyledElement|Node|String)} newElement
             *     An element to insert into this Container.
             * @param {(StyledElements.StyledElement|Node)} [refElement]
             *     Optional. An element after which `newElement` is inserted.
             *
             * @returns {StyledElements.Container}
             *     The instance on which the member is called.
             */
            appendChild: function appendChild(newElement, refElement) {
                utils.appendChild(this, newElement, refElement).forEach(addChild.bind(this));
                return this;
            },

            /**
             * Inserts the `newElement` to the beginning of this Container
             * or before the `refElement` given.
             * @since 0.7
             *
             * @param {(StyledElements.StyledElement|Node|String)} newElement
             *     An element to insert into this Container.
             * @param {(StyledElements.StyledElement|Node)} [refElement]
             *     Optional. An element before which `newElement` is inserted.
             *
             * @returns {StyledElements.Container}
             *      The instance on which the member is called.
             */
            prependChild: function prependChild(newElement, refElement) {
                utils.prependChild(this, newElement, refElement).forEach(addChild.bind(this));
                return this;
            },

            removeChild: function removeChild(element) {
                if (element == null) {
                    throw new TypeError('missing element parameter');
                }

                return this.remove(element);
            },

            repaint: function repaint(temporal) {
                temporal = temporal !== undefined ? temporal : false;

                if (this.useFullHeight) {
                    if (this.wrapperElement.classList.contains('hidden')) {
                        this.wrapperElement.style.height = "";
                        return;
                    }

                    var height = this._getUsableHeight();
                    if (height == null) {
                        return; // nothing to do
                    }

                    this.wrapperElement.style.height = (height + "px");
                }

                for (var i = 0; i < this.children.length; i++) {
                    this.children[i].repaint(temporal);
                }

                if (this.disabledLayer != null) {
                    this.disabledLayer.style.height = this.wrapperElement.scrollHeight + 'px';
                    this.disabledLayer.style.lineHeight = this.wrapperElement.clientHeight + 'px';
                }
            },

            clear: function clear() {
                this.children = [];
                this.wrapperElement.innerHTML = "";
                this.wrapperElement.scrollTop = 0;
                this.wrapperElement.scrollLeft = 0;
                if (this.disabledLayer != null) {
                    this.wrapperElement.appendChild(this.disabledLayer);
                }

                return this;
            },

            text: function (text) {
                if (text == null) {
                    return this.get().textContent;
                }

                this.children = [];
                this.wrapperElement.textContent = "" + text;
            },

            /**
             * @deprecated since version 0.6.0
             */
            isDisabled: function isDisabled() {
                return this.disabledLayer != null;
            },

            _onenabled: function _onenabled(enabled) {
                if (enabled) {
                    this.disabledLayer.parentNode.removeChild(this.disabledLayer);
                    this.disabledLayer = null;
                    this.disable_icon = null;
                } else {
                    this.disabledLayer = document.createElement('div');
                    this.disabledLayer.className = 'se-container-disable-layer';

                    this.disabled_icon = document.createElement('i');
                    this.disabled_icon.className = 'disable-icon icon-spin icon-spinner';
                    this.disabledLayer.appendChild(this.disabled_icon);

                    this.wrapperElement.appendChild(this.disabledLayer);
                    this.disabledLayer.style.height = this.wrapperElement.scrollHeight + 'px';
                    this.disabledLayer.style.lineHeight = this.wrapperElement.clientHeight + 'px';
                }
            }
        }

    });

    // ==================================================================================
    // PRIVATE MEMBERS
    // ==================================================================================

    var defaults = {
        'class': "",
        id: "",
        extraClass: "",
        tagname: 'div',
        useFullHeight: false
    };

    var addChild = function addChild(newElement) {
        /* jshint validthis: true */

        if (newElement instanceof se.StyledElement) {
            var index = this.children.indexOf(newElement);

            if (index === -1) {
                this.children.push(newElement);
            }
        }
    };

})(StyledElements, StyledElements.Utils);
<|endoftext|>


<commit_before>'use strict'

var write = require('../write')
var fastfall = require('fastfall')
var Packet = require('aedes-packet')
var through = require('through2')
var validateTopic = require('./validations').validateTopic
var topicActions = fastfall([
  authorize,
  storeSubscriptions,
  subTopic
])

function SubscribeState (client, packet, finish, granted) {
  this.client = client
  this.packet = packet
  this.finish = finish
  this.granted = granted
  this.subsIndex = 0
}

// if same subscribed topic in subs array, we pick up the last one
function _dedupe (subs) {
  var dedupeSubs = {}
  for (var i = 0; i < subs.length; i++) {
    var sub = subs[i]
    dedupeSubs[sub.topic] = sub
  }
  var ret = []
  for (var key in dedupeSubs) {
    ret.push(dedupeSubs[key])
  }
  return ret
}

function handleSubscribe (client, packet, done) {
  var broker = client.broker
  var subs = packet.subscriptions
  var granted = []

  broker._series(
    new SubscribeState(client, packet, done, granted),
    doSubscribe,
    subs.length === 1 ? subs : _dedupe(subs),
    completeSubscribe)
}

function doSubscribe (sub, done) {
  // TODO this function should not be needed
  topicActions.call(this, sub, done)
}

function authorize (sub, done) {
  var client = this.client
  var err = validateTopic(sub.topic, 'SUBSCRIBE')
  if (err) {
    return done(err)
  }
  client.broker.authorizeSubscribe(client, sub, done)
}

function blockDollarSignTopics (func) {
  return function deliverSharp (packet, cb) {
    // '$' is 36
    if (packet.topic.charCodeAt(0) === 36) {
      cb()
    } else {
      func(packet, cb)
    }
  }
}

function Subscription (qos, func) {
  this.qos = qos
  this.func = func
}

function storeSubscriptions (sub, done) {
  var packet = this.packet
  var client = this.client
  var broker = client.broker
  var perst = broker.persistence

  if (!sub) {
    this.granted.push(128)
  }

  if (packet.subscriptions.length > 0 && ++this.subsIndex < packet.subscriptions.length) {
    // TODO change aedes subscribe handle, but this fix bugs for now.
    return done(null, sub)
  }

  if (packet.restore) {
    return done(null, sub)
  }

  if (client.clean) {
    return done(null, sub)
  }

  perst.addSubscriptions(client, packet.subscriptions, function addSub (err) {
    done(err, sub)
  })
}

function subTopic (sub, done) {
  var client = this.client
  var broker = client.broker
  var func = nop

  if (!sub) {
    return done()
  }

  switch (sub.qos) {
    case 2:
    case 1:
      func = client.deliverQoS
      break
    default:
      func = client.deliver0
      break
  }

  // [MQTT-4.7.2-1]
  if (isStartsWithWildcard(sub.topic)) {
    func = blockDollarSignTopics(func)
  }

  this.granted.push(sub.qos)

  if (!client.subscriptions[sub.topic]) {
    client.subscriptions[sub.topic] = new Subscription(sub.qos, func)
    broker.subscribe(sub.topic, func, done)
  } else if (client.subscriptions[sub.topic].qos !== sub.qos) {
    broker.unsubscribe(sub.topic, client.subscriptions[sub.topic].func)
    client.subscriptions[sub.topic] = new Subscription(sub.qos, func)
    broker.subscribe(sub.topic, func, done)
  } else {
    done()
  }
}

// + is 43
// # is 35
function isStartsWithWildcard (topic) {
  var code = topic.charCodeAt(0)
  return code === 43 || code === 35
}

function completeSubscribe (err) {
  var packet = this.packet
  var client = this.client
  var broker = client.broker
  var granted = this.granted
  var done = this.finish

  if (err) {
    return done(err)
  }

  if (!packet.restore) {
    broker.emit('subscribe', packet.subscriptions, client)
  }

  if (packet.messageId) {
    write(client, new SubAck(packet, granted), nop)
  }

  // negated subscription check
  if (this.granted && this.granted[0] === 128) {
    return done()
  } else {
    done()
  }

  var persistence = broker.persistence
  var topics = []
  for (var i = 0; i < packet.subscriptions.length; i++) {
    topics.push(packet.subscriptions[i].topic)
  }
  var stream = persistence.createRetainedStreamCombi(topics)
  stream.pipe(through.obj(function sendRetained (packet, enc, cb) {
    packet = new Packet({
      cmd: packet.cmd,
      qos: packet.qos,
      topic: packet.topic,
      payload: packet.payload,
      retain: true
    }, broker)
    // this should not be deduped
    packet.brokerId = null
    client.deliverQoS(packet, cb)
  }))
}

function SubAck (packet, granted) {
  this.cmd = 'suback'
  this.messageId = packet.messageId
  this.granted = granted
}

function nop () {}

module.exports = handleSubscribe
<commit_msg>Parallelize subscribe handler (#316)<commit_after>'use strict'

var write = require('../write')
var fastfall = require('fastfall')
var Packet = require('aedes-packet')
var through = require('through2')
var validateTopic = require('./validations').validateTopic
var topicActions = fastfall([
  authorize,
  storeSubscriptions,
  subTopic
])

function SubAck (packet, granted) {
  this.cmd = 'suback'
  this.messageId = packet.messageId
  this.granted = granted
}

function Subscription (qos, func) {
  this.qos = qos
  this.func = func
}

function SubscribeState (client, packet, finish, granted) {
  this.client = client
  this.packet = packet
  this.finish = finish
  this.subState = []
}

function SubState (client, packet, granted) {
  this.client = client
  this.packet = packet
  this.granted = granted
}

// if same subscribed topic in subs array, we pick up the last one
function _dedupe (subs) {
  var dedupeSubs = {}
  for (var i = 0; i < subs.length; i++) {
    var sub = subs[i]
    dedupeSubs[sub.topic] = sub
  }
  var ret = []
  for (var key in dedupeSubs) {
    ret.push(dedupeSubs[key])
  }
  return ret
}

function handleSubscribe (client, packet, done) {
  var subs = packet.subscriptions
  client.broker._parallel(
    new SubscribeState(client, packet, done),
    doSubscribe,
    subs.length === 1 ? subs : _dedupe(subs),
    completeSubscribe)
}

function doSubscribe (sub, done) {
  var s = new SubState(this.client, this.packet, sub.qos)
  this.subState.push(s)
  topicActions.call(s, sub, done)
}

function authorize (sub, done) {
  var err = validateTopic(sub.topic, 'SUBSCRIBE')
  if (err) {
    return done(err)
  }
  var client = this.client
  client.broker.authorizeSubscribe(client, sub, done)
}

function blockDollarSignTopics (func) {
  return function deliverSharp (packet, cb) {
    // '$' is 36
    if (packet.topic.charCodeAt(0) === 36) {
      cb()
    } else {
      func(packet, cb)
    }
  }
}

function storeSubscriptions (sub, done) {
  if (!sub || typeof sub !== 'object') {
    return done(null, null)
  }

  var packet = this.packet

  if (packet.restore) {
    return done(null, sub)
  }

  var client = this.client

  if (client.clean) {
    return done(null, sub)
  }

  client.broker.persistence.addSubscriptions(client, packet.subscriptions, function addSub (err) {
    done(err, sub)
  })
}

function subTopic (sub, done) {
  if (!sub || typeof sub !== 'object') {
    this.granted = 128
    return done()
  }

  var client = this.client
  var broker = client.broker
  var topic = sub.topic
  var qos = sub.qos
  var func = qos > 0 ? client.deliverQoS : client.deliver0

  // [MQTT-4.7.2-1]
  if (isStartsWithWildcard(topic)) {
    func = blockDollarSignTopics(func)
  }

  if (!client.subscriptions[topic]) {
    client.subscriptions[topic] = new Subscription(qos, func)
    broker.subscribe(topic, func, done)
  } else if (client.subscriptions[topic].qos !== qos) {
    broker.unsubscribe(topic, client.subscriptions[topic].func)
    client.subscriptions[topic] = new Subscription(qos, func)
    broker.subscribe(topic, func, done)
  } else {
    done()
  }
}

// + is 43
// # is 35
function isStartsWithWildcard (topic) {
  var code = topic.charCodeAt(0)
  return code === 43 || code === 35
}

function completeSubscribe (err) {
  var done = this.finish

  if (err) {
    return done(err)
  }

  var packet = this.packet
  var client = this.client
  var broker = client.broker
  var granted = this.subState.map(obj => obj.granted)
  this.subState = []

  var subs = packet.subscriptions

  if (!packet.restore) {
    broker.emit('subscribe', subs, client)
  }

  if (packet.messageId) {
    write(client, new SubAck(packet, granted), nop)
  }

  // negated subscription check
  if (granted[0] === 128) {
    return done()
  } else {
    done()
  }

  var persistence = broker.persistence
  var topics = []
  for (var i = 0; i < subs.length; i++) {
    topics.push(subs[i].topic)
  }
  var stream = persistence.createRetainedStreamCombi(topics)
  stream.pipe(through.obj(function sendRetained (packet, enc, cb) {
    packet = new Packet({
      cmd: packet.cmd,
      qos: packet.qos,
      topic: packet.topic,
      payload: packet.payload,
      retain: true
    }, broker)
    // this should not be deduped
    packet.brokerId = null
    client.deliverQoS(packet, cb)
  }))
}

function nop () {}

module.exports = handleSubscribe
<|endoftext|>


<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
 * BlobServiceEx
 */

var util = require('util');
var BlobService = require('../../node_modules/azure/lib/services/blob/blobservice');
var WebResource = require('../../node_modules/azure/lib/http/webresource');
var azureutil = require('../../node_modules/azure/lib/util/util');
var BlobResult = require('../../node_modules/azure/lib/services/blob/models/blobresult');
var Constants = require('../../node_modules/azure/lib/util/constants');
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var BlobConstants = Constants.BlobConstants;
var HttpConstants = Constants.HttpConstants;

//Expose 'BlobServiceEx'.
exports = module.exports = BlobServiceEx;

/**
* Creates a new BlobServiceEx object.
*
* @constructor
* @extends {BlobServiceEx}
*
* @param {string} [storageAccount]          The storage account.
* @param {string} [storageAccessKey]        The storage access key.
* @param {string} [host]                    The host address.
* @param {object} [authenticationProvider]  The authentication provider.
*/
function BlobServiceEx(storageAccount, storageAccessKey, host, authenticationProvider) {
  BlobServiceEx.super_.call(this, storageAccount, storageAccessKey, host, authenticationProvider);
  this.apiVersion = '2012-02-12';
}

util.inherits(BlobServiceEx, BlobService);

/**
* Copies a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob.
*
* @this {BlobServiceEx}
* @param {string}             sourceContainer                             The source container name.
* @param {string}             sourceBlob                                  The source blob name.
* @param {string}             targetContainer                             The target container name.
* @param {string}             targetBlob                                  The target blob name.
* @param {object|function}    [optionsOrCallback]                         The blobs and request options.
* @param {string}             [optionsOrCallback.snapshotId]              The source blob snapshot identifier.
* @param {object}             [optionsOrCallback.metadata]                The target blob metadata key/value pairs.
* @param {string}             [optionsOrCallback.leaseId]                 The target blob lease identifier.
* @param {string}             [optionsOrCallback.sourceLeaseId]           The source blob lease identifier.
* @param {object}             [optionsOrCallback.accessConditions]        The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {object}             [optionsOrCallback.sourceAccessConditions]  The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {int}                [optionsOrCallback.timeoutIntervalInMs]     The timeout interval, in milliseconds, to use for the request.
* @param {function(error, blob, response)}  callback                      The callback function.
* @return {undefined}
*/
BlobServiceEx.prototype.copyBlobEx = function (sourceUri, targetContainer, targetBlob, optionsOrCallback, callback) {
  var options = null;
  if (typeof optionsOrCallback === 'function' && !callback) {
    callback = optionsOrCallback;
  } else {
    options = optionsOrCallback;
  }

  validateContainerName(targetContainer);
  validateBlobName(targetContainer, targetBlob);
  validateCallback(callback);

  var targetResourceName = createResourceName(targetContainer, targetBlob);

  var webResource = WebResource.put(targetResourceName)
    .withProperty(BlobConstants.ResourceTypeProperty, BlobConstants.ResourceTypes.BLOB)
    .withProperty(BlobConstants.SharedAccessPermissionProperty, BlobConstants.SharedAccessPermissions.WRITE);

  if (options) {
    webResource.addOptionalHeader(HeaderConstants.LEASE_ID_HEADER, options.leaseId);
    webResource.addOptionalHeader(HeaderConstants.SOURCE_LEASE_ID_HEADER, options.leaseId);
    webResource.addOptionalMetadataHeaders(options.metadata);
  }

  webResource.withOkCode(HttpConstants.HttpResponseCodes.ACCEPTED_CODE);

  if (options && options.snapshotId) {
    sourceUri += '?snapshot=' + options.snapshotId;
  }
  webResource.addOptionalHeader(HeaderConstants.COPY_SOURCE_HEADER, sourceUri);

  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(targetContainer, targetBlob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);

      if (options && options.metadata) {
        responseObject.blobResult.metadata = options.metadata;
      }
    }

    var finalCallback = function (returnObject) {
      var response = returnObject.response;
      if (response && response.headers) {
        response.copyStatus = response.headers['x-ms-copy-status'] || response.headers['x-ms-copy-blob-status'];
      }

      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };

    next(responseObject, finalCallback);
  };

  this.performRequest(webResource, null, options, processResponseCallback);
};

/**
* Copies a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob.
*
* @this {BlobServiceEx}
* @param {string}             targetContainer                             The target container name.
* @param {string}             targetBlob                                  The target blob name.
* @param {object|function}    [optionsOrCallback]                         The blobs and request options.
* @param {string}             [optionsOrCallback.leaseId]                 The target blob lease identifier.
* @param {object}             [optionsOrCallback.accessConditions]        The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {int}                [optionsOrCallback.timeoutIntervalInMs]     The timeout interval, in milliseconds, to use for the request.
* @param {function(error, blob, response)}  callback                      The callback function.
* @return {undefined}
*/
BlobServiceEx.prototype.copyBlobStatus = function (targetContainer, targetBlob, optionsOrCallback, callback) {
  var options = null;
  if (typeof optionsOrCallback === 'function' && !callback) {
    callback = optionsOrCallback;
  } else {
    options = optionsOrCallback;
  }

  validateContainerName(targetContainer);
  validateBlobName(targetContainer, targetBlob);
  validateCallback(callback);

  var targetResourceName = createResourceName(targetContainer, targetBlob);

  var webResource = WebResource.head(targetResourceName)
    .withProperty(BlobConstants.ResourceTypeProperty, BlobConstants.ResourceTypes.BLOB)
    .withProperty(BlobConstants.SharedAccessPermissionProperty, BlobConstants.SharedAccessPermissions.WRITE);

  if (options && options.leaseId) {
    webResource.addOptionalHeader(HeaderConstants.LEASE_ID_HEADER, options.leaseId);
    webResource.addOptionalHeader(HeaderConstants.SOURCE_LEASE_ID_HEADER, options.leaseId);
  }
  webResource.withOkCode(HttpConstants.HttpResponseCodes.ACCEPTED_CODE);
  webResource.withOkCode(HttpConstants.HttpResponseCodes.OK_CODE);

  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(targetContainer, targetBlob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
    }

    var finalCallback = function (returnObject) {
      var response = returnObject.response;
      if (response && response.headers) {
        response.copyStatus = response.headers['x-ms-copy-status'] || response.headers['x-ms-copy-blob-status'];
      }
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };

    next(responseObject, finalCallback);
  };

  this.performRequest(webResource, null, options, processResponseCallback);
};

//Non-class methods

/**
* Create resource name
*
* @param {string} containerName Container name
* @param {string} blobName      Blob name
* @return {string} The encoded resource name.
*/
function createResourceName(containerName, blobName) {
  // Resource name
  var resourceName = containerName + '/' + blobName;
  if (!containerName || containerName === '$root') {
    resourceName = blobName;
  }

  if (!blobName) {
    resourceName = containerName;
  }

  // return URI encoded resource name
  return encodeURI(resourceName);
}

/**
* Validates a container name.
*
* @param {string} containerName The container name.
* @return {undefined}
*/
function validateContainerName(containerName) {
  if (!azureutil.objectIsString(containerName) || azureutil.stringIsEmpty(containerName)) {
    throw new Error(BlobService.incorrectContainerNameErr);
  }

  if (containerName === '$root') {
    return;
  }

  if (containerName.match('^[a-z0-9][a-z0-9-]*$') === null) {
    throw new Error(BlobService.incorrectContainerNameFormatErr);
  }

  if (containerName.indexOf('--') !== -1) {
    throw new Error(BlobService.incorrectContainerNameFormatErr);
  }

  if (containerName.length < 3 || containerName.length > 63) {
    throw new Error(BlobService.incorrectContainerNameFormatErr);
  }

  if (containerName.substr(containerName.length - 1, 1) === '-') {
    throw new Error(BlobService.incorrectContainerNameFormatErr);
  }
}

/**
* Validates a blob name.
*
* @param {string} containerName The container name.
* @param {string} blobname      The blob name.
* @return {undefined}
*/
function validateBlobName(containerName, blobName) {
  if (!blobName) {
    throw new Error(BlobService.incorrectBlobNameErr);
  }

  if (containerName === '$root' && blobName.indexOf('/') !== -1) {
    throw new Error(BlobService.incorrectBlobNameFormatErr);
  }
}

/**
* Validates a callback function.
*
* @param {function} callback The callback function.
* @return {undefined}
*/
function validateCallback(callback) {
  if (!callback) {
    throw new Error(BlobService.incorrectCallbackErr);
  }
}
<commit_msg>Update http response codes<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
 * BlobServiceEx
 */

var util = require('util');
var BlobService = require('../../node_modules/azure/lib/services/blob/blobservice');
var WebResource = require('../../node_modules/azure/lib/http/webresource');
var azureutil = require('../../node_modules/azure/lib/util/util');
var BlobResult = require('../../node_modules/azure/lib/services/blob/models/blobresult');
var Constants = require('../../node_modules/azure/lib/util/constants');
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var BlobConstants = Constants.BlobConstants;
var HttpConstants = Constants.HttpConstants;

//Expose 'BlobServiceEx'.
exports = module.exports = BlobServiceEx;

/**
* Creates a new BlobServiceEx object.
*
* @constructor
* @extends {BlobServiceEx}
*
* @param {string} [storageAccount]          The storage account.
* @param {string} [storageAccessKey]        The storage access key.
* @param {string} [host]                    The host address.
* @param {object} [authenticationProvider]  The authentication provider.
*/
function BlobServiceEx(storageAccount, storageAccessKey, host, authenticationProvider) {
  BlobServiceEx.super_.call(this, storageAccount, storageAccessKey, host, authenticationProvider);
  this.apiVersion = '2012-02-12';
}

util.inherits(BlobServiceEx, BlobService);

/**
* Copies a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob.
*
* @this {BlobServiceEx}
* @param {string}             sourceContainer                             The source container name.
* @param {string}             sourceBlob                                  The source blob name.
* @param {string}             targetContainer                             The target container name.
* @param {string}             targetBlob                                  The target blob name.
* @param {object|function}    [optionsOrCallback]                         The blobs and request options.
* @param {string}             [optionsOrCallback.snapshotId]              The source blob snapshot identifier.
* @param {object}             [optionsOrCallback.metadata]                The target blob metadata key/value pairs.
* @param {string}             [optionsOrCallback.leaseId]                 The target blob lease identifier.
* @param {string}             [optionsOrCallback.sourceLeaseId]           The source blob lease identifier.
* @param {object}             [optionsOrCallback.accessConditions]        The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {object}             [optionsOrCallback.sourceAccessConditions]  The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {int}                [optionsOrCallback.timeoutIntervalInMs]     The timeout interval, in milliseconds, to use for the request.
* @param {function(error, blob, response)}  callback                      The callback function.
* @return {undefined}
*/
BlobServiceEx.prototype.copyBlobEx = function (sourceUri, targetContainer, targetBlob, optionsOrCallback, callback) {
  var options = null;
  if (typeof optionsOrCallback === 'function' && !callback) {
    callback = optionsOrCallback;
  } else {
    options = optionsOrCallback;
  }

  validateContainerName(targetContainer);
  validateBlobName(targetContainer, targetBlob);
  validateCallback(callback);

  var targetResourceName = createResourceName(targetContainer, targetBlob);

  var webResource = WebResource.put(targetResourceName)
    .withProperty(BlobConstants.ResourceTypeProperty, BlobConstants.ResourceTypes.BLOB)
    .withProperty(BlobConstants.SharedAccessPermissionProperty, BlobConstants.SharedAccessPermissions.WRITE);

  if (options) {
    webResource.addOptionalHeader(HeaderConstants.LEASE_ID_HEADER, options.leaseId);
    webResource.addOptionalHeader(HeaderConstants.SOURCE_LEASE_ID_HEADER, options.leaseId);
    webResource.addOptionalMetadataHeaders(options.metadata);
  }

  webResource.withOkCode(HttpConstants.HttpResponseCodes.Accepted);

  if (options && options.snapshotId) {
    sourceUri += '?snapshot=' + options.snapshotId;
  }
  webResource.addOptionalHeader(HeaderConstants.COPY_SOURCE_HEADER, sourceUri);

  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(targetContainer, targetBlob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);

      if (options && options.metadata) {
        responseObject.blobResult.metadata = options.metadata;
      }
    }

    var finalCallback = function (returnObject) {
      var response = returnObject.response;
      if (response && response.headers) {
        response.copyStatus = response.headers['x-ms-copy-status'] || response.headers['x-ms-copy-blob-status'];
      }

      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };

    next(responseObject, finalCallback);
  };

  this.performRequest(webResource, null, options, processResponseCallback);
};

/**
* Copies a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob.
*
* @this {BlobServiceEx}
* @param {string}             targetContainer                             The target container name.
* @param {string}             targetBlob                                  The target blob name.
* @param {object|function}    [optionsOrCallback]                         The blobs and request options.
* @param {string}             [optionsOrCallback.leaseId]                 The target blob lease identifier.
* @param {object}             [optionsOrCallback.accessConditions]        The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {int}                [optionsOrCallback.timeoutIntervalInMs]     The timeout interval, in milliseconds, to use for the request.
* @param {function(error, blob, response)}  callback                      The callback function.
* @return {undefined}
*/
BlobServiceEx.prototype.copyBlobStatus = function (targetContainer, targetBlob, optionsOrCallback, callback) {
  var options = null;
  if (typeof optionsOrCallback === 'function' && !callback) {
    callback = optionsOrCallback;
  } else {
    options = optionsOrCallback;
  }

  validateContainerName(targetContainer);
  validateBlobName(targetContainer, targetBlob);
  validateCallback(callback);

  var targetResourceName = createResourceName(targetContainer, targetBlob);

  var webResource = WebResource.head(targetResourceName)
    .withProperty(BlobConstants.ResourceTypeProperty, BlobConstants.ResourceTypes.BLOB)
    .withProperty(BlobConstants.SharedAccessPermissionProperty, BlobConstants.SharedAccessPermissions.WRITE);

  if (options && options.leaseId) {
    webResource.addOptionalHeader(HeaderConstants.LEASE_ID_HEADER, options.leaseId);
    webResource.addOptionalHeader(HeaderConstants.SOURCE_LEASE_ID_HEADER, options.leaseId);
  }
  webResource.withOkCode(HttpConstants.HttpResponseCodes.Accepted);
  webResource.withOkCode(HttpConstants.HttpResponseCodes.Ok);

  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(targetContainer, targetBlob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
    }

    var finalCallback = function (returnObject) {
      var response = returnObject.response;
      if (response && response.headers) {
        response.copyStatus = response.headers['x-ms-copy-status'] || response.headers['x-ms-copy-blob-status'];
      }
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };

    next(responseObject, finalCallback);
  };

  this.performRequest(webResource, null, options, processResponseCallback);
};

//Non-class methods

/**
* Create resource name
*
* @param {string} containerName Container name
* @param {string} blobName      Blob name
* @return {string} The encoded resource name.
*/
function createResourceName(containerName, blobName) {
  // Resource name
  var resourceName = containerName + '/' + blobName;
  if (!containerName || containerName === '$root') {
    resourceName = blobName;
  }

  if (!blobName) {
    resourceName = containerName;
  }

  // return URI encoded resource name
  return encodeURI(resourceName);
}

/**
* Validates a container name.
*
* @param {string} containerName The container name.
* @return {undefined}
*/
function validateContainerName(containerName) {
  if (!azureutil.objectIsString(containerName) || azureutil.stringIsEmpty(containerName)) {
    throw new Error(BlobService.incorrectContainerNameErr);
  }

  if (containerName === '$root') {
    return;
  }

  if (containerName.match('^[a-z0-9][a-z0-9-]*$') === null) {
    throw new Error(BlobService.incorrectContainerNameFormatErr);
  }

  if (containerName.indexOf('--') !== -1) {
    throw new Error(BlobService.incorrectContainerNameFormatErr);
  }

  if (containerName.length < 3 || containerName.length > 63) {
    throw new Error(BlobService.incorrectContainerNameFormatErr);
  }

  if (containerName.substr(containerName.length - 1, 1) === '-') {
    throw new Error(BlobService.incorrectContainerNameFormatErr);
  }
}

/**
* Validates a blob name.
*
* @param {string} containerName The container name.
* @param {string} blobname      The blob name.
* @return {undefined}
*/
function validateBlobName(containerName, blobName) {
  if (!blobName) {
    throw new Error(BlobService.incorrectBlobNameErr);
  }

  if (containerName === '$root' && blobName.indexOf('/') !== -1) {
    throw new Error(BlobService.incorrectBlobNameFormatErr);
  }
}

/**
* Validates a callback function.
*
* @param {function} callback The callback function.
* @return {undefined}
*/
function validateCallback(callback) {
  if (!callback) {
    throw new Error(BlobService.incorrectCallbackErr);
  }
}
<|endoftext|>


<commit_before>
'use strict';

module.exports = snmpPingJobFactory;

snmpPingJobFactory.$provide = 'Job.Snmp.Ping';
snmpPingJobFactory.$inject = [
    'Job.Base',
    'JobUtils.Snmptool',
    'Logger',
    'Util'
];

function snmpPingJobFactory(BaseJob, Snmptool, Logger, util) {
    var logger = Logger.initialize(snmpPingJobFactory);

    function SnmpPingJob(options, context, taskId) {
        SnmpPingJob.super_.call(this, logger, options, context, taskId);
        this.nodeId = context.target;
        this.snmptool = new Snmptool(options.host, options.community);
    }
    util.inherits(SnmpPingJob, BaseJob);

    SnmpPingJob.prototype._run = function _run() {
        var self = this;

        return this.snmptool.ping()
        .then(function () {
            self._done();
        })
        .catch(function (err){
            logger.error("Host did not respond.", { error: err });
            self._done(err);
        });
    };

    return SnmpPingJob;
}
<commit_msg>Remove unused snmp ping job<commit_after><|endoftext|>


<commit_before>var React = require('react'),
    TwitterTypeahead = require('typeahead.js'),
    extend = require("extend"),
    ReactTypeahead;

ReactTypeahead = React.createClass({displayName: "ReactTypeahead",
	/**
	* 'initOptions' method
     * This method sets up the typeahead with initial config parameters. The first set is default
     * and the other set is defined by the
     */
    initOptions: function () {
    	var defaultMinLength = 2, defaultDivId = 'autosuggest', config = {};

    	if(!this.props.bloodhound)
    		this.props.bloodhound = {};
    	if(!this.props.typeahead)
    		this.props.typeahead = {};
    	if(!this.props.datasource)
    		this.props.datasource = {};

    	if (!this.props.bloodhound.remote.url)
            throw new Error('Oops:( The url is missing from the bloodhound config');

        var defaults = {
        	     bloodhound: {
        	     	     datumTokenizer: Bloodhound.tokenizers.whitespace,
                         queryTokenizer: Bloodhound.tokenizers.whitespace
                 },
        	     typeahead: {
        	     	minLength: defaultMinLength,
  			        hint: true,
                    highlight: true
        	     },
        	     datasource: {
        	     	displayProperty: 'value',
        	        queryStr: '%QUERY'
        	     }
        };

        config.bloodhound = extend(true, {}, defaults.bloodhound, this.props.bloodhound);
        config.typeahead = extend(true, {}, defaults.typeahead, this.props.typeahead);
        config.datasource = extend(true, {}, defaults.datasource, this.props.datasource);
        config.componentId = (this.props.typeahead.id)?this.props.typeahead.id:defaultDivId

        return config;
    },
	/**
     * 'componentDidMount' method
     * Initializes react with the typeahead component.
     */
    componentDidMount: function () {
        var self = this,
            options = this.initOptions();

        var remoteCall = new Bloodhound(options.bloodhound);
        options.datasource.source = remoteCall;
        var typeaheadInput = React.findDOMNode(self);
        if(typeaheadInput)
        	this.typeahead = typeaheadInput.typeahead(options.typeahead, options.datasource);

    },

    componentWillUnmount: function () {
        this.typeahead	;
    }
  });

module.exports = ReactTypeahead;<commit_msg>Initial Commit<commit_after>var React = require('react'),
    TwitterTypeahead = require('typeahead.js'),
    extend = require("extend"),
    ReactTypeahead;

ReactTypeahead = React.createClass({displayName: "ReactTypeahead",
	/**
	* 'initOptions' method
     * This method sets up the typeahead with initial config parameters. The first set is default
     * and the other set is defined by the
     */
    initOptions: function () {
    	var defaultMinLength = 2, config = {};

    	if(!this.props.bloodhound)
    		this.props.bloodhound = {};
    	if(!this.props.typeahead)
    		this.props.typeahead = {};
    	if(!this.props.datasource)
    		this.props.datasource = {};

    	if (!this.props.bloodhound.remote.url)
            throw new Error('Oops:( The url is missing from the bloodhound config');

        var defaults = {
        	     bloodhound: {
        	     	     datumTokenizer: Bloodhound.tokenizers.whitespace,
                         queryTokenizer: Bloodhound.tokenizers.whitespace
                 },
        	     typeahead: {
        	     	minLength: defaultMinLength,
  			        hint: true,
                    highlight: true
        	     },
        	     datasource: {
        	     	displayProperty: 'value',
        	        queryStr: '%QUERY'
        	     }
        };

        config.bloodhound = extend(true, {}, defaults.bloodhound, this.props.bloodhound);
        config.typeahead = extend(true, {}, defaults.typeahead, this.props.typeahead);
        config.datasource = extend(true, {}, defaults.datasource, this.props.datasource);

        return config;
    },
	/**
     * 'componentDidMount' method
     * Initializes react with the typeahead component.
     */
    componentDidMount: function () {
        var self = this,
            options = this.initOptions();

        var remoteCall = new Bloodhound(options.bloodhound);
        options.datasource.source = remoteCall;
        var typeaheadInput = React.findDOMNode(self);
        if(typeaheadInput)
        	this.typeahead = typeaheadInput.typeahead(options.typeahead, options.datasource);

    },

    render: function () {
        return (
            <input class="typeahead" type="text" placeholder={this.props.placeHolder}>
        );
    }
  });

module.exports = ReactTypeahead;<|endoftext|>