<commit_before>/**
 * Express configuration
 */

'use strict';

var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var setCookie = require('set-cookie');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var session = require('express-session')
var path = require('path');
var config = require('./environment');
var forge = require('node-forge');
var rawbody = require('raw-body');
var _ = require('lodash');

module.exports = function(app) {
  var env = app.get('env');

  var salt = forge.random.getBytesSync(128);
  var key = forge.pkcs5.pbkdf2(config.secrets.session, salt, 4, 16);
  var iv = forge.random.getBytesSync(16);
  var encryptObj = {
    key: forge.util.encode64(key),
    salt: forge.util.encode64(salt),
    iv: forge.util.encode64(iv)
  }
  config.encryptionObj = encryptObj;
  //console.log("encrypt value:",config.encryptionObj);

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.set(session({
    cookie : {
      httpOnly: true, secure: true, maxAge: null
    }
  }));
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser());

  function hasSql(value) {
    if (value === null || value === undefined) {
        return false;
    }
    // sql regex reference: http://www.symantec.com/connect/articles/detection-sql-injection-and-cross-site-scripting-attacks
    var sql_meta = new RegExp('(%27)|(\')|(--)|(%23)|(#)', 'i');
    if(sql_meta.test(value)){
        return true;
    }
    var sql_meta2 = new RegExp('((%3D)|(=))[^\n]*((%27)|(\')|(--)|(%3B)|(;))', 'i');
    if(sql_meta2.test(value)){
        return true;
    }
    var sql_typical = new RegExp('w*((%27)|(\'))((%6F)|o|(%4F))((%72)|r|(%52))', 'i');
    if(sql_typical.test(value)){
        return true;
    }
    var sql_union = new RegExp('((%27)|(\'))union', 'i');
    if(sql_union.test(value)){
        return true;
    }
    var sql_keywords = new RegExp('\\b(ALTER|CREATE|WHILE|AND|OR|NOT IN|LEFT|RIGHT|DELETE|DECLARE|DROP|EXEC(UTE){0,1}|INSERT( +INTO){0,1}|MERGE|SELECT|UPDATE|UNION( +ALL){0,1})\\b','i');
    if(sql_keywords.test(value)){
        return true;
    }

    var sql_keywords2 = new RegExp('\\b(ADD|EXTERNAL PROCEDURE|ALL|FETCH|PUBLIC|ALTER|FILE|RAISERROR|AND|FILLFACTOR|READ|ANY|FOR|READTEXT|AS|FOREIGN|RECONFIGURE|ASC|FREETEXT|REFERENCES|AUTHORIZATION|FREETEXTTABLE|REPLICATION|BACKUP|FROM|RESTORE|BEGIN|FULL|RESTRICT|BETWEEN|FUNCTION|RETURN|BREAK|GOTO|REVERT|BROWSE|GRANT|REVOKE|BULK|GROUP|RIGHT|BY|HAVING|ROLLBACK|CASCADE|HOLDLOCK|ROWCOUNT|CASE|IDENTITY|ROWGUIDCOL|CHECK|IDENTITY_INSERT|RULE|CHECKPOINT|IDENTITYCOL|SAVE|CLOSE|IF|SCHEMA|CLUSTERED|IN|SECURITYAUDIT|COALESCE|INDEX|SELECT|COLLATE|INNER|SEMANTICKEYPHRASETABLE|COLUMN|INSERT|SEMANTICSIMILARITYDETAILSTABLE|COMMIT|INTERSECT|SEMANTICSIMILARITYTABLE|COMPUTE|INTO|SESSION_USER|CONSTRAINT|IS|SET|CONTAINS|JOIN|SETUSER|CONTAINSTABLE|KEY|SHUTDOWN|CONTINUE|KILL|SOME|CONVERT|LEFT|STATISTICS|CREATE|LIKE|SYSTEM_USER|CROSS|LINENO|TABLE|CURRENT|LOAD|TABLESAMPLE|CURRENT_DATE|MERGE|TEXTSIZE|CURRENT_TIME|NATIONAL|THEN|CURRENT_TIMESTAMP|NOCHECK|TO|CURRENT_USER|NONCLUSTERED|TOP|CURSOR|NOT|TRAN|DATABASE|NULL|TRANSACTION|DBCC|NULLIF|TRIGGER|DEALLOCATE|OF|TRUNCATE|DECLARE|OFF|TRY_CONVERT|DEFAULT|OFFSETS|TSEQUAL|DELETE|ON|UNION|DENY|OPEN|UNIQUE|DESC|OPENDATASOURCE|UNPIVOT|DISK|OPENQUERY|UPDATE|DISTINCT|OPENROWSET|UPDATETEXT|DISTRIBUTED|OPENXML|USE|DOUBLE|OPTION|USER|DROP|OR|VALUES|DUMP|ORDER|VARYING|ELSE|OUTER|VIEW|END|OVER|WAITFOR|ERRLVL|PERCENT|WHEN|ESCAPE|PIVOT|WHERE|EXCEPT|PLAN|WHILE|EXEC|PRECISION|WITH|EXECUTE|PRIMARY|WITHIN GROUP|EXISTS|PRINT|WRITETEXT|EXIT|PROC)\\b','i');
    if(sql_keywords2.test(value)){
        return true;
    }
    return false;
  }

  app.use(['/auth','/api','/encryption'], function(req, res, next){

    var containsSql = false;

    if (req.originalUrl !== null && req.originalUrl !== undefined) {
        if (hasSql(decodeURI(req.originalUrl)) === true) {
            containsSql = true;
        }
    }

    if(containsSql === false)
    {
      _.forEach(req.body, function(n,key){
       if(containsSql) return;
        if(hasSql(n))
        {
          containsSql = true;
        }
      });
    }

    if(containsSql === false){
      next();
    } else {
        res.send(403);
    }

  });

  /*app.use(function(req, res, next){
      res.locals.session = req.session;
      next();
  });*/

  app.use(function(req, res, next) {
    setCookie('io', 'connectSIDCookieValue', {
      res: res,
    	path: '/socket.io/',
    	httpOnly: true,
    	secure:true,
    	expires:0 //at the end of the session
    });
    next();
  });

  app.use(function(req,res,next){
    if(req.headers.prsessionkey){
      var userName = req.headers.prsessionkey.split('::')[0];
      var timeStampKey = req.headers.prsessionkey.split('::')[1];
      res.header("Access-Control-Allow-Credentials", true);
      if(config.prSessionStore[userName] && config.prSessionStore[userName][timeStampKey])
      {
        var lastPing = config.prSessionStore[userName][timeStampKey];
        var timeDiff = ((new Date()).getTime() - lastPing)/1000;
        if(timeDiff > 30)
        {
          return res.json(401, 'Session Expired/Not Authorized');
        }
        else
        {
          next();
        }
      }
      else
      {
        return res.json(401, 'Session Expired/Not Authorized');
      }
    }
    else
    {
      if(req.url.indexOf("/api/") != -1 && !config.bypassAuth)
      {
        return res.json(401, 'Session Expired/Not authorized');
      }
      else
      {
        next();
      }
    }

  });

  // Configure bypassAuth according to environment
  if(env === 'development')
    config.bypassAuth = true;
  else if(env === 'test')
    config.bypassAuth = true;
  else if(env === 'stable')
    config.bypassAuth = false;
  else if(env === 'production')
    config.bypassAuth = false;
  /*if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }*/

  //if ('development' === env || 'test' === env) {
    //app.use(require('connect-livereload')());
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'client')));
    app.set('appPath', process.env.APP_PATH);
    //console.log('Express config.root %d, appPath %s', config.root, app.get('appPath'));
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  //}
};<commit_msg>PR-4490 WASA Scan remediation- Removed X-PoweredBy header variable<commit_after>/**
 * Express configuration
 */

'use strict';

var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var setCookie = require('set-cookie');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var session = require('express-session')
var path = require('path');
var config = require('./environment');
var forge = require('node-forge');
var rawbody = require('raw-body');
var _ = require('lodash');

module.exports = function(app) {
  var env = app.get('env');

  var salt = forge.random.getBytesSync(128);
  var key = forge.pkcs5.pbkdf2(config.secrets.session, salt, 4, 16);
  var iv = forge.random.getBytesSync(16);
  var encryptObj = {
    key: forge.util.encode64(key),
    salt: forge.util.encode64(salt),
    iv: forge.util.encode64(iv)
  }
  config.encryptionObj = encryptObj;
  //console.log("encrypt value:",config.encryptionObj);

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.set(session({
    cookie : {
      httpOnly: true, secure: true, maxAge: null
    }
  }));
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser());
  app.disable('x-powered-by');

  function hasSql(value) {
    if (value === null || value === undefined) {
        return false;
    }
    // sql regex reference: http://www.symantec.com/connect/articles/detection-sql-injection-and-cross-site-scripting-attacks
    var sql_meta = new RegExp('(%27)|(\')|(--)|(%23)|(#)', 'i');
    if(sql_meta.test(value)){
        return true;
    }
    var sql_meta2 = new RegExp('((%3D)|(=))[^\n]*((%27)|(\')|(--)|(%3B)|(;))', 'i');
    if(sql_meta2.test(value)){
        return true;
    }
    var sql_typical = new RegExp('w*((%27)|(\'))((%6F)|o|(%4F))((%72)|r|(%52))', 'i');
    if(sql_typical.test(value)){
        return true;
    }
    var sql_union = new RegExp('((%27)|(\'))union', 'i');
    if(sql_union.test(value)){
        return true;
    }
    var sql_keywords = new RegExp('\\b(ALTER|CREATE|WHILE|AND|OR|NOT IN|LEFT|RIGHT|DELETE|DECLARE|DROP|EXEC(UTE){0,1}|INSERT( +INTO){0,1}|MERGE|SELECT|UPDATE|UNION( +ALL){0,1})\\b','i');
    if(sql_keywords.test(value)){
        return true;
    }

    var sql_keywords2 = new RegExp('\\b(ADD|EXTERNAL PROCEDURE|ALL|FETCH|PUBLIC|ALTER|FILE|RAISERROR|AND|FILLFACTOR|READ|ANY|FOR|READTEXT|AS|FOREIGN|RECONFIGURE|ASC|FREETEXT|REFERENCES|AUTHORIZATION|FREETEXTTABLE|REPLICATION|BACKUP|FROM|RESTORE|BEGIN|FULL|RESTRICT|BETWEEN|FUNCTION|RETURN|BREAK|GOTO|REVERT|BROWSE|GRANT|REVOKE|BULK|GROUP|RIGHT|BY|HAVING|ROLLBACK|CASCADE|HOLDLOCK|ROWCOUNT|CASE|IDENTITY|ROWGUIDCOL|CHECK|IDENTITY_INSERT|RULE|CHECKPOINT|IDENTITYCOL|SAVE|CLOSE|IF|SCHEMA|CLUSTERED|IN|SECURITYAUDIT|COALESCE|INDEX|SELECT|COLLATE|INNER|SEMANTICKEYPHRASETABLE|COLUMN|INSERT|SEMANTICSIMILARITYDETAILSTABLE|COMMIT|INTERSECT|SEMANTICSIMILARITYTABLE|COMPUTE|INTO|SESSION_USER|CONSTRAINT|IS|SET|CONTAINS|JOIN|SETUSER|CONTAINSTABLE|KEY|SHUTDOWN|CONTINUE|KILL|SOME|CONVERT|LEFT|STATISTICS|CREATE|LIKE|SYSTEM_USER|CROSS|LINENO|TABLE|CURRENT|LOAD|TABLESAMPLE|CURRENT_DATE|MERGE|TEXTSIZE|CURRENT_TIME|NATIONAL|THEN|CURRENT_TIMESTAMP|NOCHECK|TO|CURRENT_USER|NONCLUSTERED|TOP|CURSOR|NOT|TRAN|DATABASE|NULL|TRANSACTION|DBCC|NULLIF|TRIGGER|DEALLOCATE|OF|TRUNCATE|DECLARE|OFF|TRY_CONVERT|DEFAULT|OFFSETS|TSEQUAL|DELETE|ON|UNION|DENY|OPEN|UNIQUE|DESC|OPENDATASOURCE|UNPIVOT|DISK|OPENQUERY|UPDATE|DISTINCT|OPENROWSET|UPDATETEXT|DISTRIBUTED|OPENXML|USE|DOUBLE|OPTION|USER|DROP|OR|VALUES|DUMP|ORDER|VARYING|ELSE|OUTER|VIEW|END|OVER|WAITFOR|ERRLVL|PERCENT|WHEN|ESCAPE|PIVOT|WHERE|EXCEPT|PLAN|WHILE|EXEC|PRECISION|WITH|EXECUTE|PRIMARY|WITHIN GROUP|EXISTS|PRINT|WRITETEXT|EXIT|PROC)\\b','i');
    if(sql_keywords2.test(value)){
        return true;
    }
    return false;
  }

  app.use(['/auth','/api','/encryption'], function(req, res, next){

    var containsSql = false;

    if (req.originalUrl !== null && req.originalUrl !== undefined) {
        if (hasSql(decodeURI(req.originalUrl)) === true) {
            containsSql = true;
        }
    }

    if(containsSql === false)
    {
      _.forEach(req.body, function(n,key){
       if(containsSql) return;
        if(hasSql(n))
        {
          containsSql = true;
        }
      });
    }

    if(containsSql === false){
      next();
    } else {
        res.send(403);
    }

  });

  /*app.use(function(req, res, next){
      res.locals.session = req.session;
      next();
  });*/

  app.use(function(req, res, next) {
    setCookie('io', 'connectSIDCookieValue', {
      res: res,
    	path: '/socket.io/',
    	httpOnly: true,
    	secure:true,
    	expires:0 //at the end of the session
    });
    next();
  });

  app.use(function(req,res,next){
    if(req.headers.prsessionkey){
      var userName = req.headers.prsessionkey.split('::')[0];
      var timeStampKey = req.headers.prsessionkey.split('::')[1];
      res.header("Access-Control-Allow-Credentials", true);
      if(config.prSessionStore[userName] && config.prSessionStore[userName][timeStampKey])
      {
        var lastPing = config.prSessionStore[userName][timeStampKey];
        var timeDiff = ((new Date()).getTime() - lastPing)/1000;
        if(timeDiff > 30)
        {
          return res.json(401, 'Session Expired/Not Authorized');
        }
        else
        {
          next();
        }
      }
      else
      {
        return res.json(401, 'Session Expired/Not Authorized');
      }
    }
    else
    {
      if(req.url.indexOf("/api/") != -1 && !config.bypassAuth)
      {
        return res.json(401, 'Session Expired/Not authorized');
      }
      else
      {
        next();
      }
    }

  });

  // Configure bypassAuth according to environment
  if(env === 'development')
    config.bypassAuth = true;
  else if(env === 'test')
    config.bypassAuth = true;
  else if(env === 'stable')
    config.bypassAuth = false;
  else if(env === 'production')
    config.bypassAuth = false;
  /*if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }*/

  //if ('development' === env || 'test' === env) {
    //app.use(require('connect-livereload')());
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'client')));
    app.set('appPath', process.env.APP_PATH);
    //console.log('Express config.root %d, appPath %s', config.root, app.get('appPath'));
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  //}
};<|endoftext|>


<commit_before>
import { Router, Route, Link, browserHistory } from 'react-router'
import React, { Component } from 'react';
import * as firebase from 'firebase';
class SchoolEvent extends Component{
  constructor(props){
    super(props);
    this.state = {
      eventData: {}
    }
  }
  componentDidMount(){
    var cursor = firebase.database().ref("Events/"+this.props.params.eventId);
    if(cursor != null){
      this.setState({eventData: cursor})
    }else{
      alert("Error Not Found!")
    }

  }

  render(){
    return(

        <ProjectActions event={this.state.eventData} eventId = {this.props.params.eventId}/>

    )
  }
}

class ProjectActions extends Component{

  deleteEvent = () => {
    this.props.event.remove();
  }
  render(){
    return(

        Project Actions

 Project ID: {this.props.eventId}

          Delete Event

)
  }
}

export default SchoolEvent;
<commit_msg>Test Commit<commit_after>
import { Router, Route, Link, browserHistory } from 'react-router'
import React, { Component } from 'react';
import * as firebase from 'firebase';
class SchoolEvent extends Component{
  constructor(props){
    super(props);
    this.state = {
      eventData: {}
    }
  }
  componentDidMount(){
    var cursor = firebase.database().ref("Events/"+this.props.params.eventId);
    if(cursor != null){
      this.setState({eventData: cursor})
    }else{
      alert("Error Not Found!");
      //test
    }

  }

  render(){
    return(

        <ProjectActions event={this.state.eventData} eventId = {this.props.params.eventId}/>

    )
  }
}

class ProjectActions extends Component{

  deleteEvent = () => {
    this.props.event.remove();
  }
  render(){
    return(

        Project Actions

 Project ID: {this.props.eventId}

          Delete Event

)
  }
}

export default SchoolEvent;
<|endoftext|>


<commit_before>
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="i18n-msg/i18n-msg.html">
<link rel="import" href="vaadin-grid/vaadin-grid.html">
<link rel="import" href="vaadin-grid/vaadin-grid-filter.html">
<link rel="import" href="iron-ajax/iron-ajax.html">

<dom-module id="sig-accounting-list">
	<template>

		<vaadin-grid id="accountingGrid">
			<vaadin-grid-column width="24ex" flex-grow="2">
				<template class="header">
					<vaadin-grid-filter
							aria-label="[[i18n.timeStamp]]"
							path="date"
							value="[[filterTimeStamp]]">
						<input
								placeholder="[[i18n.timeStamp]]"
								value="{{filterTimeStamp::input}}"
								focus-target>
					</vaadin-grid-filter>
				</template>
				<template>[[item.date]]</template>
			</vaadin-grid-column>
			<vaadin-grid-column width="8ex" flex-grow="8">
				<template class="header">
					<vaadin-grid-filter
							aria-label="[[i18n.clientIdentity]]"
							path="nasIdentifier"
							value="[[filterclientIdentityAcc]]">
						<input
								placeholder="[[i18n.clientIdentity]]"
								value="{{filterclientIdentityAcc::input}}"
								focus-target>
					</vaadin-grid-filter>
				</template>
				<template>[[item.nasIdentifier]]</template>
			</vaadin-grid-column>
			<vaadin-grid-column-group>
				<template class="header">

[[i18n.seconds]]

				</template>
				<vaadin-grid-column width="15ex" flex-grow="1">
					<template class="header">
						<vaadin-grid-filter
								aria-label="[[i18n.sessionDur]]"
								path="acctSessiontime"
								value="[[filteracctSessiontime]]">
							<input
									placeholder="[[i18n.sessionDur]]"
									value="{{filteracctSessiontime::input}}"
									focus-target>
						</vaadin-grid-filter>
					</template>
					<template>[[item.acctSessiontime]]</template>
				</vaadin-grid-column>
			</vaadin-grid-column-group>
			<vaadin-grid-column-group>
				<template class="header">

[[i18n.bytes]]

				</template>
				<vaadin-grid-column width="10ex" flex-grow="1">
					<template class="header">
						<vaadin-grid-filter
								aria-label="[[i18n.out]]"
								path="acctOutputoctets"
								value="[[filterout]]">
							<input
									placeholder="[[i18n.out]]"
									value="{{filterout::input}}"
									focus-target>
						</vaadin-grid-filter>
					</template>
					<template>[[item.acctOutputoctets]]</template>
				</vaadin-grid-column>
				<vaadin-grid-column width="10ex" flex-grow="1">
					<template class="header">
						<vaadin-grid-filter
								aria-label="[[i18n.in]]"
								path="acctInputoctets"
								value="[[filterin]]">
							<input
									placeholder="[[i18n.in]]"
									value="{{filterin::input}}"
									focus-target>
						</vaadin-grid-filter>
					</template>
					<template>[[item.acctInputoctets]]</template>
				</vaadin-grid-column>
				<vaadin-grid-column width="10ex" flex-grow="1">
					<template class="header">
						<vaadin-grid-filter
								aria-label="[[i18n.totalo]]"
								path="acctTotaloctets"
								value="[[filtertotal]]">
							<input
									placeholder="[[i18n.totalo]]"
									value="{{filtertotal::input}}"
									focus-target>
						</vaadin-grid-filter>
					</template>
					<template>[[item.acctTotaloctets]]</template>
				</vaadin-grid-column>
			</vaadin-grid-column-group>
			<vaadin-grid-column width="12ex" flex-grow="1">
				<template class="header">
					<vaadin-grid-filter
							aria-label="[[i18n.price]]"
							path="prices"
							value="[[filterPrices]]">
						<input
								placeholder="[[i18n.price]]"
								value="{{filterPrices::input}}"
								focus-target>
					</vaadin-grid-filter>
				</template>
				<template>[[item.prices]]</template>
			</vaadin-grid-column>
			<vaadin-grid-column width="12ex" flex-grow="1">
				<template class="header">
					<vaadin-grid-filter
							aria-label="[[i18n.userName]]"
							path="username"
							value="[[filterUserName]]">
						<input
								placeholder="[[i18n.userName]]"
								value="{{filterUserName::input}}"
								focus-target>
					</vaadin-grid-filter>
				</template>
				<template>[[item.username]]</template>
			</vaadin-grid-column>
			<vaadin-grid-column width="8ex" flex-grow="2">
				<template class="header">
					<vaadin-grid-filter
							aria-label="[[i18n.type]]"
							path="type"
							value="[[filterType]]">
						<input
								placeholder="[[i18n.type]]"
								value="{{filterType::input}}"
								focus-target>
					</vaadin-grid-filter>
				</template>
				<template>[[item.type]]</template>
			</vaadin-grid-column>
		</vaadin-grid>
		<paper-toast id="accountingErrorToast" duration="0">
			<paper-button
					class="yellow-button"
					onclick="accountingErrorToast.toggle()">
				Close
			</paper-button>
		</paper-toast>
		<iron-ajax id="getAccounting"
				url="/usageManagement/v1/usage"
				rejectWithRequest>
		</iron-ajax>
	</template>

</dom-module>
<commit_msg>upgrade acounting module to polymer 3<commit_after>/**
 * @license
 * Copyright (c) 2020 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@polymer/iron-ajax/iron-ajax.js';
import '@polymer/paper-fab/paper-fab.js';
import '@polymer/iron-icons/iron-icons.js';
import '@vaadin/vaadin-grid/vaadin-grid.js';
import '@vaadin/vaadin-grid/vaadin-grid-filter.js';
import '@vaadin/vaadin-grid/vaadin-grid-column-group.js';
import './style-element.js'

class accountingList extends PolymerElement {
	static get template() {
		return html`

			<vaadin-grid
					id="accountingGrid"
					loading="{{loading}}">
				<vaadin-grid-column width="24ex" flex-grow="2">
					<template class="header">
						<vaadin-grid-filter
								aria-label="time stamp"
								path="date"
								value="{{filterTimeStamp}}">
							<input
									placeholder="Time Stamp"
									value="{{filterTimeStamp::input}}"
									focus-target>
						</vaadin-grid-filter>
					</template>
					<template>[[item.date]]</template>
				</vaadin-grid-column>
				<vaadin-grid-column width="8ex" flex-grow="8">
					<template class="header">
						<vaadin-grid-filter
								aria-label="client identity"
								path="nasIdentifier"
								value="{{filterclientIdentityAcc}}">
							<input
									placeholder="Client Identity"
									value="{{filterclientIdentityAcc::input}}"
									focus-target>
						</vaadin-grid-filter>
					</template>
					<template>[[item.nasIdentifier]]</template>
				</vaadin-grid-column>
				<vaadin-grid-column-group>
					<template class="header">

Seconds

					</template>
					<vaadin-grid-column width="15ex" flex-grow="1">
						<template class="header">
							<vaadin-grid-filter
									aria-label="duration"
									path="acctSessiontime"
									value="{{filteracctSessiontime}}">
								<input
										placeholder="Duration"
										value="{{filteracctSessiontime::input}}"
										focus-target>
							</vaadin-grid-filter>
						</template>
						<template>[[item.acctSessiontime]]</template>
					</vaadin-grid-column>
				</vaadin-grid-column-group>
				<vaadin-grid-column-group>
					<template class="header">

Bytes

					</template>
					<vaadin-grid-column width="10ex" flex-grow="1">
						<template class="header">
							<vaadin-grid-filter
									aria-label="out"
									path="acctOutputoctets"
									value="{{filterout}}">
								<input
										placeholder="Out"
										value="{{filterout::input}}"
										focus-target>
							</vaadin-grid-filter>
						</template>
						<template>[[item.acctOutputoctets]]</template>
					</vaadin-grid-column>
					<vaadin-grid-column width="10ex" flex-grow="1">
						<template class="header">
							<vaadin-grid-filter
									aria-label="in"
									path="acctInputoctets"
									value="{{filterin}}">
								<input
										placeholder="In"
										value="{{filterin::input}}"
										focus-target>
							</vaadin-grid-filter>
						</template>
						<template>[[item.acctInputoctets]]</template>
					</vaadin-grid-column>
					<vaadin-grid-column width="10ex" flex-grow="1">
						<template class="header">
							<vaadin-grid-filter
									aria-label="total"
									path="acctTotaloctets"
									value="{{filtertotal}}">
								<input
										placeholder="Total"
										value="{{filtertotal::input}}"
										focus-target>
							</vaadin-grid-filter>
						</template>
						<template>[[item.acctTotaloctets]]</template>
					</vaadin-grid-column>
				</vaadin-grid-column-group>
				<vaadin-grid-column width="12ex" flex-grow="1">
					<template class="header">
						<vaadin-grid-filter
								aria-label="price"
								path="prices"
								value="{{filterPrices}}">
							<input
									placeholder="Price"
									value="{{filterPrices::input}}"
									focus-target>
						</vaadin-grid-filter>
					</template>
					<template>[[item.prices]]</template>
				</vaadin-grid-column>
				<vaadin-grid-column width="12ex" flex-grow="1">
					<template class="header">
						<vaadin-grid-filter
								aria-label="user name"
								path="username"
								value="{{filterUserName}}">
							<input
									placeholder="User Name"
									value="{{filterUserName::input}}"
									focus-target>
						</vaadin-grid-filter>
					</template>
					<template>[[item.username]]</template>
				</vaadin-grid-column>
				<vaadin-grid-column width="8ex" flex-grow="2">
					<template class="header">
						<vaadin-grid-filter
								aria-label="type"
								path="type"
								value="{{filterType}}">
							<input
									placeholder="Type"
									value="{{filterType::input}}"
									focus-target>
						</vaadin-grid-filter>
					</template>
					<template>[[item.type]]</template>
				</vaadin-grid-column>
			</vaadin-grid>
			<iron-ajax id="getAccounting"
					url="/usageManagement/v1/usage"
					rejectWithRequest>
			</iron-ajax>
		`;
	}

	static get properties() {
		return {
         loading: {
            type: Boolean,
            notify: true
         },
         etag: {
            type: String,
            value: null
         },
			filterTimeStamp: {
				type: Boolean,
				observer: '_filterChanged'
			},
			filterclientIdentityAcc: {
				type: Boolean,
				observer: '_filterChanged'
			},
			filteracctSessiontime: {
				type: Boolean,
				observer: '_filterChanged'
			},
			filterout: {
				type: Boolean,
				observer: '_filterChanged'
			},
			filterin: {
				type: Boolean,
				observer: '_filterChanged'
			},
			filtertotal: {
				type: Boolean,
				observer: '_filterChanged'
			},
			filterPrices: {
				type: Boolean,
				observer: '_filterChanged'
			},
			filterUserName: {
				type: Boolean,
				observer: '_filterChanged'
			},
			filterType: {
				type: Boolean,
				observer: '_filterChanged'
			}
		}
	}

   ready() {
      super.ready();
      var grid = this.shadowRoot.getElementById('accountingGrid');
      grid.dataProvider = this._getAccounting;
   }

	_getAccounting(params, callback) {
		var grid = this;
		var accountingList = document.body.querySelector('sig-app').shadowRoot.querySelector('sig-accounting-list');
		var ajax = accountingList.shadowRoot.getElementById('getAccounting');
		delete ajax.params['date'];
		delete ajax.params['nasIdentifier'];
		delete ajax.params['acctSessiontime'];
		delete ajax.params['acctOutputoctets'];
		delete ajax.params['acctInputoctets'];
		delete ajax.params['acctTotaloctets'];
		delete ajax.params['filter'];
		ajax.params['type'] = "AAAAccountingUsage";
		function checkHead(param) {
			return param.path == "date" || param.path == "status";
		}
		var head;
		params.filters.filter(checkHead).forEach(function(filter) {
			if (filter.value) {
				ajax.params[filter.path] = filter.value;
			}
		});
		function checkChar(param) {
			return param.path != "date" && param.path != "status";
		}
		params.filters.filter(checkChar).forEach(function(filter) {
			if (filter.value) {
				if (!ajax.params['filter']) {
					ajax.params['filter'] = "\"[{usageCharacteristic.contains=[";
				} else {
					ajax.params['filter'] += ",";
				}
				if(isNaN(filter.value)) {
					ajax.params['filter'] += "{name=" + filter.path + ",value.like=[" + filter.value + "%]}";
				} else {
					ajax.params['filter'] += "{name=" + filter.path + ",value.gte=" + filter.value + "%}";
				}
			}
		});
		if (ajax.params['filter']) {
			ajax.params['filter'] += "]}]\"";
		}
		var handleAjaxResponse = function(request) {
		if (request) {
			accountingList.etag = request.xhr.getResponseHeader('ETag');
			var range = request.xhr.getResponseHeader('Content-Range');
			var range1 = range.split("/");
			var range2 = range1[0].split("-");
			if (range1[1] != "*") {
				grid.size = Number(range1[1]);
			} else {
				grid.size = Number(range2[1]) + grid.pageSize * 2;
			}
			var vaadinItems = new Array();
			for (var index in request.response) {
				var newRecord = new Object();
				newRecord.date = request.response[index].date;
				function checkChar2(characteristic) {
					return characteristic.name == "nasIdentifier";
				}
				var index2 = request.response[index].usageCharacteristic.findIndex(checkChar2);
				if(index2 != -1) {
					newRecord.nasIdentifier = request.response[index].usageCharacteristic[index2].value;
				}
				function checkChar3(characteristic) {
					return characteristic.name == "acctSessionTime";
				}
				var index3 = request.response[index].usageCharacteristic.findIndex(checkChar3);
				if(index3 != -1) {
					newRecord.acctSessiontime = request.response[index].usageCharacteristic[index3].value;
				}
				function checkChar4(characteristic) {
					return characteristic.name == "outputOctets";
				}
				var index4 = request.response[index].usageCharacteristic.findIndex(checkChar4);
				if(index4 != -1) {
					newRecord.acctOutputoctets = request.response[index].usageCharacteristic[index4].value;
				}
				function checkChar5(characteristic) {
					return characteristic.name == "inputOctets";
				}
				var index5 = request.response[index].usageCharacteristic.findIndex(checkChar5);
				if(index5 != -1) {
					newRecord.acctInputoctets = request.response[index].usageCharacteristic[index5].value;
				}
				function checkChar6(characteristic) {
					return characteristic.name == "totalOctets";
				}
				var index6 = request.response[index].usageCharacteristic.findIndex(checkChar6);
				if(index6 != -1) {
					newRecord.acctTotaloctets = request.response[index].usageCharacteristic[index6].value;
				}
				function checkChar7(characteristic) {
					return characteristic.name == "username";
				}
				var username1 = request.response[index].usageCharacteristic.find(checkChar7);
				if (username1 != undefined) {
					newRecord.username = username1.value;
				}
				function checkChar8(characteristic) {
					return characteristic.name == "type";
				}
				var index8 = request.response[index].usageCharacteristic.findIndex(checkChar8);
				if (index8 != -1) {
					newRecord.type = request.response[index].usageCharacteristic[index8].value;
				}
				for(var indexTax in request.response[index].ratedProductUsage) {
					var taxObj = request.response[index].ratedProductUsage[indexTax].taxExcludedRatingAmount;
					if(taxObj) {
						newRecord.prices = taxObj;
					}
				}
				vaadinItems[index] = newRecord;
			}
			callback(vaadinItems);
		} else {
			grid.size = 0;
			callback([]);
		}
	}
	var handleAjaxError = function(error) {
		accountingList.etag = null;
		var toast = document.body.querySelector('sig-app').shadowRoot.getElementById('restError');
		toast.text = error;
		toast.open();
		if(!grid.size) {
			grid.size = 0;
		}
		callback([]);
	}
	if (ajax.loading) {
		ajax.lastRequest.completes.then(function(request) {
			var startRange = params.page * params.pageSize + 1;
			var endRange = startRange + params.pageSize - 1;
			ajax.headers['Range'] = "items=" + startRange + "-" + endRange;
			if (accountingList.etag && params.page > 0) {
				ajax.headers['If-Range'] = accountingList.etag;
			} else {
				delete ajax.headers['If-Range'];
			}
			return ajax.generateRequest().completes;
				}, handleAjaxError).then(handleAjaxResponse, handleAjaxError);
		} else {
			var startRange = params.page * params.pageSize + 1;
			var endRange = startRange + params.pageSize - 1;
			ajax.headers['Range'] = "items=" + startRange + "-" + endRange;
			if (accountingList.etag && params.page > 0) {
				ajax.headers['If-Range'] = accountingList.etag;
			} else {
				delete ajax.headers['If-Range'];
			}
			ajax.generateRequest().completes.then(handleAjaxResponse, handleAjaxError);
		}
	}

   _filterChanged(filter) {
      this.etag = null;
      var grid = this.shadowRoot.getElementById('accountingGrid');
      grid.size = 0;
   }

}

window.customElements.define('sig-accounting-list', accountingList);

<|endoftext|>


<commit_before><commit_msg>Added it("should understand array length")<commit_after><|endoftext|>


<commit_before>var Iconv = require('./iconv').Iconv,
   assert = require('assert');

var iconv = new Iconv('UTF-8', 'UTF-16');

var utf8 = new Buffer(20000000);
for (var i = 0; i < utf8.length; i++) {
  utf8[i] = 97 + i % 26; // cycle from 'a' to 'z'.
}
var utf16 = iconv.convert(utf8);

// 2 bytes per character + 2 bytes for BOM
assert.equal(utf16.length, utf8.length * 2 + 2);

// test for BOM
assert.equal(utf16[0], 0xff);
assert.equal(utf16[1], 0xfe);

for (i = 0; i < utf8.length; ++i) {
  assert.equal(utf16[2 + i * 2], utf8[i]);
  assert.equal(utf16[2 + i * 2 + 1], 0);
}

<commit_msg>Don't require() from local directory.<commit_after>var Iconv = require('iconv').Iconv,
   assert = require('assert');

var iconv = new Iconv('UTF-8', 'UTF-16');

var utf8 = new Buffer(20000000);
for (var i = 0; i < utf8.length; i++) {
  utf8[i] = 97 + i % 26; // cycle from 'a' to 'z'.
}
var utf16 = iconv.convert(utf8);

// 2 bytes per character + 2 bytes for BOM
assert.equal(utf16.length, utf8.length * 2 + 2);

// test for BOM
assert.equal(utf16[0], 0xff);
assert.equal(utf16[1], 0xfe);

for (i = 0; i < utf8.length; ++i) {
  assert.equal(utf16[2 + i * 2], utf8[i]);
  assert.equal(utf16[2 + i * 2 + 1], 0);
}

<|endoftext|>


<commit_before><commit_msg>AboutArrays tests passing<commit_after><|endoftext|>


<commit_before>// Copyright 2012 Joyent, Inc.  All rights reserved.

var Logger = require('bunyan');
var restify = require('restify');
var libuuid = require('libuuid');
var util = require('util');
function uuid() {
    return (libuuid.create());
}

var CNAPI = require('../lib/index').CNAPI;

// --- Globals

var CNAPI_URL = 'http://' + (process.env.CNAPI_IP || '10.99.99.22');

var SERVER = null;
var ZONE = '0777a40e-8b41-11e2-be6f-7f3bf8fcea65';
var TASK = null;
var DATASET_UUID = 'fd2cc906-8938-11e3-beab-4359c665ac99';
var CUSTOMER = process.env.UFDS_ADMIN_UUID;
var cnapi;

// --- Helpers

function waitForVmState(state, callback) {
    var finished = false;
    var error;

    var timeout = setTimeout(function () {
        if (finished) {
            return;
        }

        if (error) {
            callback(error);
            return;
        } else {
            callback(new Error('timed out waiting on vm state'));
            return;
        }
    }, 30000);

    function check() {
        cnapi.getVm(SERVER, ZONE, function (err, vm) {
            error = err;
            if (err) {
                setTimeout(check, 3000);
                return;
            }
            console.log('vm state was %s', vm.state);

            if (vm.state === state) {
                clearTimeout(timeout);
                callback();
                return;
            }

            setTimeout(check, 3000);
        });
    }

    check();
}

function waitForTask(callback) {
    var finished = false;
    var error;

    var tasktimeout;

    var timeout = setTimeout(function () {
        clearTimeout(tasktimeout);
        if (finished) {
            return;
        }

        if (error) {
            callback(error);
            return;
        } else {
            callback(new Error('timed out waiting on task'));
            return;
        }
    }, 50000);

    function check() {
        cnapi.getTask(TASK, function (err, task) {
            error = err;
            if (finished) {
                return;
            }
            if (err) {
                console.warn(err.message);
                if (err.message === 'no such task found') {
                    setTimeout(check, 3000);
                    return;
                }
                clearTimeout(timeout);
                finished = true;
                callback(err);
                return;
            }

            console.log('task status %s', task.status);

            if (task.status == 'failure') {
                clearTimeout(timeout);
                finished = true;
                callback(new Error(
                    'Task failed ' + util.inspect(task, { depth: null })));
                return;
            }

            if (task.status == 'complete') {
                console.warn('ALL DONE');
                clearTimeout(timeout);
                finished = true;
                callback(null);
                return;
            }

            tasktimeout = setTimeout(check, 3000);
            return;
        });
    }

    check();
}

// --- Tests

exports.setUp = function (callback) {
    cnapi = new CNAPI({
        url: CNAPI_URL,
        retry: {
            retries: 1,
            minTimeout: 1000
        },
        log: new Logger({
            name: 'cnapi_unit_test',
            stream: process.stderr,
            level: (process.env.LOG_LEVEL || 'info'),
            serializers: Logger.stdSerializers
        }),
        agent: false
    });
    callback();
};

exports.test_list_servers = function (test) {
    cnapi.listServers({ headnode: true }, function (err, servers) {
        test.ifError(err);
        test.ok(servers);
        SERVER = servers[0].uuid;
        test.done();
    });
};

exports.test_get_server = function (test) {
    cnapi.getServer(SERVER, function (err, server) {
        test.ifError(err);
        test.ok(server);
        test.done();
    });
};

exports.test_create_vm = function (test) {
    var opts = {
        uuid: ZONE,
        owner_uuid: CUSTOMER,
        dataset_uuid:  '01b2c898-945f-11e1-a523-af1afbe22822',
        brand: 'joyent',
        image_uuid: '01b2c898-945f-11e1-a523-af1afbe22822',
        image: {
            uuid: '01b2c898-945f-11e1-a523-af1afbe22822',
            files: [
                {
                    sha1: '97f20b32c2016782257176fb58a35e5044f05840',
                    size: 46271847,
                    compression: 'bzip2'
                }
            ]
        },
        ram: 128
    };

    cnapi.createVm(SERVER, opts, function (err, task) {
        test.ifError(err);
        test.ok(task);
        TASK = task.id;
        test.done();
    });
};

exports.test_wait_for_running = function (test) {
    waitForTask(function (err) {
        test.ifError(err);

        waitForVmState('running', function (err2) {
            test.ifError(err2);
            test.done();
        });
    });
};

exports.test_get_vm = function (test) {
    setTimeout(function () {
        cnapi.getVm(SERVER, ZONE, function (err, vm) {
            test.ifError(err);
            test.ok(vm);
            test.done();
        });
    }, 10000);
};

exports.test_stop_vm = function (test) {
    cnapi.stopVm(SERVER, ZONE, function (err, task) {
        test.ifError(err);
        test.ok(task);
        TASK = task.id;
        test.done();
    });
};

exports.test_wait_for_stopped = function (test) {
    waitForTask(function (err) {
        test.ifError(err);
        waitForVmState('stopped', function (err2) {
            test.ifError(err2);

            test.done();
        });
    });
};

// Wait 3 seconds after the job completes
exports.test_start_vm = function (test) {
    setTimeout(function () {
        cnapi.startVm(SERVER, ZONE, function (err, task) {
            test.ifError(err);
            test.ok(task);
            TASK = task.id;
            test.done();
        });
    }, 6000);
};

exports.test_wait_for_started = function (test) {
    waitForTask(function (err) {
        test.ifError(err);
        waitForVmState('running', function (err2) {
            test.ifError(err2);
            test.done();
        });
    });
};

exports.test_reboot_vm = function (test) {
    setTimeout(function () {
        cnapi.rebootVm(SERVER, ZONE, function (err, task) {
            test.ifError(err);
            test.ok(task);
            TASK = task.id;
            test.done();
        });
    }, 6000);
};

exports.test_wait_for_reboot = function (test) {
    waitForTask(function (err) {
        test.ifError(err);
        waitForVmState('running', function (err2) {
            test.ifError(err2);
            test.done();
        });
    });
};

exports.test_delete_vm = function (test) {
    setTimeout(function () {
        cnapi.deleteVm(SERVER, ZONE, function (err, task) {
            test.ifError(err);
            test.ok(task);
            TASK = task.id;
            test.done();
        });
    }, 3000);
};

exports.test_wait_for_deleted = function (test) {
    waitForTask(function (err) {
        test.ifError(err);
        test.done();
    });
};

exports.test_command_execute = function (test) {
    var script = '#!/usr/bin/bash\n\necho Hello\n';

    cnapi.commandExecute(SERVER, script, function (err) {
        test.ifError(err);
        test.done();
    });
};

exports.test_command_execute_with_env = function (test) {
    var script = '#!/usr/bin/bash\n\necho Hello\n';
    var env = { FOO: 'bar' };

    cnapi.commandExecute(SERVER, script, { env: env }, function (err) {
        test.ifError(err);
        test.done();
    });
};

// this test is sadly not ideal -- we'd like to check it picks only one server,
// and it's the correct server, but that only works if the test is run with
// a standup containing multiple CNs. With a standup of only COAL, this test
// is ambiguous.
exports.test_capacity_1 = function (test) {
    var headers = { 'x-request-id': 12345 };

    cnapi.capacity([SERVER], { headers: headers }, function (err, res) {
        test.ifError(err);
        test.equal(typeof (res), 'object');
        test.equal(typeof (res.capacities), 'object');
        test.equal(typeof (res.errors), 'object');
        test.equal(Object.keys(res.capacities).length, 1);

        var server = res.capacities[SERVER];
        test.equal(typeof (server.cpu), 'number');
        test.equal(typeof (server.ram), 'number');
        test.equal(typeof (server.disk), 'number');

        test.done();
    });
};

exports.test_capacity_2 = function (test) {
    cnapi.capacity(null, function (err, res) {
        test.ifError(err);
        test.equal(typeof (res), 'object');
        test.equal(typeof (res.capacities), 'object');
        test.equal(typeof (res.errors), 'object');
        test.ok(Object.keys(res.capacities).length >= 1);

        Object.keys(res.capacities).forEach(function (serverUuid) {
            var server = res.capacities[serverUuid];
            test.equal(typeof (server.cpu), 'number');
            test.equal(typeof (server.ram), 'number');
            test.equal(typeof (server.disk), 'number');
        });

        test.done();
    });
};
<commit_msg>CNAPI-368: Fix image referenced in test<commit_after>// Copyright 2012 Joyent, Inc.  All rights reserved.

var Logger = require('bunyan');
var restify = require('restify');
var libuuid = require('libuuid');
var util = require('util');
function uuid() {
    return (libuuid.create());
}

var CNAPI = require('../lib/index').CNAPI;

// --- Globals

var CNAPI_URL = 'http://' + (process.env.CNAPI_IP || '10.99.99.22');

var SERVER = null;
var ZONE = '0777a40e-8b41-11e2-be6f-7f3bf8fcea65';
var TASK = null;
var DATASET_UUID = 'fd2cc906-8938-11e3-beab-4359c665ac99';
var CUSTOMER = process.env.UFDS_ADMIN_UUID;
var cnapi;

// --- Helpers

function waitForVmState(state, callback) {
    var finished = false;
    var error;

    var timeout = setTimeout(function () {
        if (finished) {
            return;
        }

        if (error) {
            callback(error);
            return;
        } else {
            callback(new Error('timed out waiting on vm state'));
            return;
        }
    }, 30000);

    function check() {
        cnapi.getVm(SERVER, ZONE, function (err, vm) {
            error = err;
            if (err) {
                setTimeout(check, 3000);
                return;
            }
            console.log('vm state was %s', vm.state);

            if (vm.state === state) {
                clearTimeout(timeout);
                callback();
                return;
            }

            setTimeout(check, 3000);
        });
    }

    check();
}

function waitForTask(callback) {
    var finished = false;
    var error;

    var tasktimeout;

    var timeout = setTimeout(function () {
        clearTimeout(tasktimeout);
        if (finished) {
            return;
        }

        if (error) {
            callback(error);
            return;
        } else {
            callback(new Error('timed out waiting on task'));
            return;
        }
    }, 50000);

    function check() {
        cnapi.getTask(TASK, function (err, task) {
            error = err;
            if (finished) {
                return;
            }
            if (err) {
                console.warn(err.message);
                if (err.message === 'no such task found') {
                    setTimeout(check, 3000);
                    return;
                }
                clearTimeout(timeout);
                finished = true;
                callback(err);
                return;
            }

            console.log('task status %s', task.status);

            if (task.status == 'failure') {
                clearTimeout(timeout);
                finished = true;
                callback(new Error(
                    'Task failed ' + util.inspect(task, { depth: null })));
                return;
            }

            if (task.status == 'complete') {
                console.warn('ALL DONE');
                clearTimeout(timeout);
                finished = true;
                callback(null);
                return;
            }

            tasktimeout = setTimeout(check, 3000);
            return;
        });
    }

    check();
}

// --- Tests

exports.setUp = function (callback) {
    cnapi = new CNAPI({
        url: CNAPI_URL,
        retry: {
            retries: 1,
            minTimeout: 1000
        },
        log: new Logger({
            name: 'cnapi_unit_test',
            stream: process.stderr,
            level: (process.env.LOG_LEVEL || 'info'),
            serializers: Logger.stdSerializers
        }),
        agent: false
    });
    callback();
};

exports.test_list_servers = function (test) {
    cnapi.listServers({ headnode: true }, function (err, servers) {
        test.ifError(err);
        test.ok(servers);
        SERVER = servers[0].uuid;
        test.done();
    });
};

exports.test_get_server = function (test) {
    cnapi.getServer(SERVER, function (err, server) {
        test.ifError(err);
        test.ok(server);
        test.done();
    });
};

exports.test_create_vm = function (test) {
    var opts = {
        uuid: ZONE,
        owner_uuid: CUSTOMER,
        dataset_uuid:  'fd2cc906-8938-11e3-beab-4359c665ac99',
        brand: 'joyent',
        image_uuid: 'fd2cc906-8938-11e3-beab-4359c665ac99',
        image: {
            uuid: 'fd2cc906-8938-11e3-beab-4359c665ac99',
            "files": [
                {
                    "sha1": "97f20b32c2016782257176fb58a35e5044f05840",
                    "size": 46271847,
                    "compression": "bzip2"
                }
            ],
        },
        ram: 128
    };

    cnapi.createVm(SERVER, opts, function (err, task) {
        test.ifError(err);
        test.ok(task);
        TASK = task.id;
        test.done();
    });
};

exports.test_wait_for_running = function (test) {
    waitForTask(function (err) {
        test.ifError(err);

        waitForVmState('running', function (err2) {
            test.ifError(err2);
            test.done();
        });
    });
};

exports.test_get_vm = function (test) {
    setTimeout(function () {
        cnapi.getVm(SERVER, ZONE, function (err, vm) {
            test.ifError(err);
            test.ok(vm);
            test.done();
        });
    }, 10000);
};

exports.test_stop_vm = function (test) {
    cnapi.stopVm(SERVER, ZONE, function (err, task) {
        test.ifError(err);
        test.ok(task);
        TASK = task.id;
        test.done();
    });
};

exports.test_wait_for_stopped = function (test) {
    waitForTask(function (err) {
        test.ifError(err);
        waitForVmState('stopped', function (err2) {
            test.ifError(err2);

            test.done();
        });
    });
};

// Wait 3 seconds after the job completes
exports.test_start_vm = function (test) {
    setTimeout(function () {
        cnapi.startVm(SERVER, ZONE, function (err, task) {
            test.ifError(err);
            test.ok(task);
            TASK = task.id;
            test.done();
        });
    }, 6000);
};

exports.test_wait_for_started = function (test) {
    waitForTask(function (err) {
        test.ifError(err);
        waitForVmState('running', function (err2) {
            test.ifError(err2);
            test.done();
        });
    });
};

exports.test_reboot_vm = function (test) {
    setTimeout(function () {
        cnapi.rebootVm(SERVER, ZONE, function (err, task) {
            test.ifError(err);
            test.ok(task);
            TASK = task.id;
            test.done();
        });
    }, 6000);
};

exports.test_wait_for_reboot = function (test) {
    waitForTask(function (err) {
        test.ifError(err);
        waitForVmState('running', function (err2) {
            test.ifError(err2);
            test.done();
        });
    });
};

exports.test_delete_vm = function (test) {
    setTimeout(function () {
        cnapi.deleteVm(SERVER, ZONE, function (err, task) {
            test.ifError(err);
            test.ok(task);
            TASK = task.id;
            test.done();
        });
    }, 3000);
};

exports.test_wait_for_deleted = function (test) {
    waitForTask(function (err) {
        test.ifError(err);
        test.done();
    });
};

exports.test_command_execute = function (test) {
    var script = '#!/usr/bin/bash\n\necho Hello\n';

    cnapi.commandExecute(SERVER, script, function (err) {
        test.ifError(err);
        test.done();
    });
};

exports.test_command_execute_with_env = function (test) {
    var script = '#!/usr/bin/bash\n\necho Hello\n';
    var env = { FOO: 'bar' };

    cnapi.commandExecute(SERVER, script, { env: env }, function (err) {
        test.ifError(err);
        test.done();
    });
};

// this test is sadly not ideal -- we'd like to check it picks only one server,
// and it's the correct server, but that only works if the test is run with
// a standup containing multiple CNs. With a standup of only COAL, this test
// is ambiguous.
exports.test_capacity_1 = function (test) {
    var headers = { 'x-request-id': 12345 };

    cnapi.capacity([SERVER], { headers: headers }, function (err, res) {
        test.ifError(err);
        test.equal(typeof (res), 'object');
        test.equal(typeof (res.capacities), 'object');
        test.equal(typeof (res.errors), 'object');
        test.equal(Object.keys(res.capacities).length, 1);

        var server = res.capacities[SERVER];
        test.equal(typeof (server.cpu), 'number');
        test.equal(typeof (server.ram), 'number');
        test.equal(typeof (server.disk), 'number');

        test.done();
    });
};

exports.test_capacity_2 = function (test) {
    cnapi.capacity(null, function (err, res) {
        test.ifError(err);
        test.equal(typeof (res), 'object');
        test.equal(typeof (res.capacities), 'object');
        test.equal(typeof (res.errors), 'object');
        test.ok(Object.keys(res.capacities).length >= 1);

        Object.keys(res.capacities).forEach(function (serverUuid) {
            var server = res.capacities[serverUuid];
            test.equal(typeof (server.cpu), 'number');
            test.equal(typeof (server.ram), 'number');
            test.equal(typeof (server.disk), 'number');
        });

        test.done();
    });
};
<|endoftext|>


<commit_before>// speedtest.js
// author: bashow
// 2020/07/18

// sudo apt18nstall chromium-browser
// sudo apt install npm

// npm i puppeteer
// npm i speedline

// node speedtest.js

const puppeteer = require('puppeteer-core');

var url = process.argv[2];

(async () => {
  const browser = await puppeteer.launch({executablePath: '/usr/bin/chromium-browser'});
  const page = await browser.newPage();

  try {
    await page.goto(url, { waitUntil: 'networkidle0' });

    await page.waitFor(40000);

    let frames = page.frames();

    if (frames.find( f => f.url().indexOf("test-ipv6") > 0) ) {
      var ipv6frame = frames.find(
          f =>
            f.url().indexOf("test-ipv6") > 0);

      const ipv6rttItem = await ipv6frame.$('#pingText');
      const ipv6rtt = await (await ipv6rttItem.getProperty('textContent')).jsonValue();

      const ipv6jitItem = await ipv6frame.$('#jitText');
      const ipv6jit = await (await ipv6jitItem.getProperty('textContent')).jsonValue();

      const ipv6dlItem = await ipv6frame.$('#dlText');
      const ipv6dl = await (await ipv6dlItem.getProperty('textContent')).jsonValue();

      const ipv6ulItem = await ipv6frame.$('#ulText');
      const ipv6ul = await (await ipv6ulItem.getProperty('textContent')).jsonValue();

      console.log('IPv6_RTT:' + ipv6rtt);
      console.log('IPv6_JIT:' + ipv6jit);
      console.log('IPv6_PDL:' + ipv6dl);
      console.log('IPv6_UL:' + ipv6ul);

    }

    if (frames.find( f => f.url().indexOf("test-ipv4") > 0) ) {
      var ipv4frame = frames.find(
          f =>
            f.url().indexOf("test-ipv4") > 0);

      const ipv4rttItem = await ipv4frame.$('#pingText');
      const ipv4rtt = await (await ipv4rttItem.getProperty('textContent')).jsonValue();

      const ipv4jitItem = await ipv4frame.$('#jitText');
      const ipv4jit = await (await ipv4jitItem.getProperty('textContent')).jsonValue();

      const ipv4dlItem = await ipv4frame.$('#dlText');
      const ipv4dl = await (await ipv4dlItem.getProperty('textContent')).jsonValue();

      const ipv4ulItem = await ipv4frame.$('#ulText');
      const ipv4ul = await (await ipv4ulItem.getProperty('textContent')).jsonValue();

      console.log('IPv4_RTT:' + ipv4rtt);
      console.log('IPv4_JIT:' + ipv4jit);
      console.log('IPv4_DL:' + ipv4dl);
      console.log('IPv4_UL:' + ipv4ul);

    }

  } catch (e) {
        console.error(e);
  }

  // await page.screenshot({path: 'screenshot.png'});
  await browser.close();

})();

<commit_msg>Fixed speedtest.js<commit_after>// speedtest.js
// author: bashow
// 2020/07/18

// sudo apt18nstall chromium-browser
// sudo apt install npm

// npm i puppeteer
// npm i speedline

// node speedtest.js

const puppeteer = require('puppeteer-core');

var url = process.argv[2];

(async () => {
  const browser = await puppeteer.launch({executablePath: '/usr/bin/chromium-browser'});
  const page = await browser.newPage();

  try {
    await page.goto(url, { waitUntil: 'networkidle0' });

    await page.waitFor(40000);

    let frames = page.frames();

    if (frames.find( f => f.url().indexOf("test-ipv6") > 0) ) {
      var ipv6frame = frames.find(
          f =>
            f.url().indexOf("test-ipv6") > 0);

      const ipv6rttItem = await ipv6frame.$('#pingText');
      const ipv6rtt = await (await ipv6rttItem.getProperty('textContent')).jsonValue();

      const ipv6jitItem = await ipv6frame.$('#jitText');
      const ipv6jit = await (await ipv6jitItem.getProperty('textContent')).jsonValue();

      const ipv6dlItem = await ipv6frame.$('#dlText');
      const ipv6dl = await (await ipv6dlItem.getProperty('textContent')).jsonValue();

      const ipv6ulItem = await ipv6frame.$('#ulText');
      const ipv6ul = await (await ipv6ulItem.getProperty('textContent')).jsonValue();

      console.log('IPv6_RTT:' + ipv6rtt);
      console.log('IPv6_JIT:' + ipv6jit);
      console.log('IPv6_DL:' + ipv6dl);
      console.log('IPv6_UL:' + ipv6ul);

    }

    if (frames.find( f => f.url().indexOf("test-ipv4") > 0) ) {
      var ipv4frame = frames.find(
          f =>
            f.url().indexOf("test-ipv4") > 0);

      const ipv4rttItem = await ipv4frame.$('#pingText');
      const ipv4rtt = await (await ipv4rttItem.getProperty('textContent')).jsonValue();

      const ipv4jitItem = await ipv4frame.$('#jitText');
      const ipv4jit = await (await ipv4jitItem.getProperty('textContent')).jsonValue();

      const ipv4dlItem = await ipv4frame.$('#dlText');
      const ipv4dl = await (await ipv4dlItem.getProperty('textContent')).jsonValue();

      const ipv4ulItem = await ipv4frame.$('#ulText');
      const ipv4ul = await (await ipv4ulItem.getProperty('textContent')).jsonValue();

      console.log('IPv4_RTT:' + ipv4rtt);
      console.log('IPv4_JIT:' + ipv4jit);
      console.log('IPv4_DL:' + ipv4dl);
      console.log('IPv4_UL:' + ipv4ul);

    }

  } catch (e) {
        console.error(e);
  }

  // await page.screenshot({path: 'screenshot.png'});
  await browser.close();

})();

<|endoftext|>


<commit_before>import fs from 'fs'
import test from 'tape'
import sinon from 'sinon'
import index, {formats} from '../src/commit-msg'

test('index', t => {
  t.equal(typeof index, 'object', 'default export is an object')
  t.end()
})

test('index.check()', t => {
  const readFileSync = sinon.stub(fs, 'readFileSync')
  const base = sinon.stub(formats, 'base')

  index.check('base', './test/fixtures/COMMIT_EDITMSG')

  t.throws(() => { index.check('nein')}, 'calls an existing format')
  t.assert(readFileSync.calledOnce, 'calls fs.readFileSync')
  t.assert(base.calledOnce, 'calls formats.base')

  formats.base.restore()

  t.end()
})

test('formats', t => {
  t.equal(typeof formats, 'object', 'is an object')
  t.end()
})

test('formats.base()', t => {
  const under = '..........' // 10
  const equal = '..................................................' // 50
  const over = '...................................................' // 51

  t.equal(formats.base(under), true)
  t.equal(formats.base(equal), true)
  t.equal(formats.base(over), false)
  t.assert(typeof formats.base, 'is a function')
  t.end()
})
<commit_msg>Use helper to create test strings<commit_after>import fs from 'fs'
import test from 'tape'
import sinon from 'sinon'
import index, {formats} from '../src/commit-msg'

test('index', t => {
  t.equal(typeof index, 'object', 'default export is an object')
  t.end()
})

test('index.check()', t => {
  const readFileSync = sinon.stub(fs, 'readFileSync')
  const base = sinon.stub(formats, 'base')

  index.check('base', './test/fixtures/COMMIT_EDITMSG')

  t.throws(() => { index.check('nein')}, 'calls an existing format')
  t.assert(readFileSync.calledOnce, 'calls fs.readFileSync')
  t.assert(base.calledOnce, 'calls formats.base')

  formats.base.restore()

  t.end()
})

test('formats', t => {
  t.equal(typeof formats, 'object', 'is an object')
  t.end()
})

test('formats.base()', t => {
  const under = buildString(10)
  const equal = buildString(50)
  const over = buildString(51)

  t.equal(formats.base(under), true)
  t.equal(formats.base(equal), true)
  t.equal(formats.base(over), false)
  t.assert(typeof formats.base, 'is a function')
  t.end()
})

function buildString (length) {
  let string = ''

  for (let i = 0; i < length; i++) {
    string += '_'
  }

  return string
}
<|endoftext|>


<commit_before>getVersion = function(){
  return 'v1.2.1';
};<commit_msg>Bump version: 1.2.2<commit_after>getVersion = function(){
  return 'v1.2.2';
};<|endoftext|>


<commit_before>var rewire = require("rewire");
var Connection = rewire("../lib/connection");

var events = require("events");
var sinon = require("sinon");
var Q = require("q");

describe("Connection", function() {
	describe('constructor', function () {
		var originalEnv;

		before(function() {
			originalEnv = process.env.NODE_ENV;
		});

		after(function() {
			process.env.NODE_ENV = originalEnv;
		})

		beforeEach(function() {
			process.env.NODE_ENV = "";
		})

		// Issue #50
		it("should use gateway.sandbox.push.apple.com as the default connection address", function () {
			expect(Connection().options.address).to.equal("gateway.sandbox.push.apple.com");
		});

		it("should use gateway.push.apple.com when NODE_ENV=production", function () {
			process.env.NODE_ENV = "production";
			expect(Connection().options.address).to.equal("gateway.push.apple.com");
		});

		it("should give precedence to production flag over NODE_ENV=production", function () {
			process.env.NODE_ENV = "production";
			expect(Connection({ production: false }).options.address).to.equal("gateway.sandbox.push.apple.com");
		});

		it("should use gateway.push.apple.com when production:true", function () {
			expect(Connection({production:true}).options.address).to.equal("gateway.push.apple.com");
		});

		it("should use a custom address when passed", function () {
			expect(Connection({address: "testaddress"}).options.address).to.equal("testaddress");
		});

		describe("address is passed", function() {
			it("sets production to true when using production address", function() {
				expect(Connection({address: "gateway.push.apple.com"}).options.production).to.be.true;
			});

			it("sets production to false when using sandbox address", function() {
				process.env.NODE_ENV = "production";
				expect(Connection({address: "gateway.sandbox.push.apple.com"}).options.production).to.be.false;
			});
		});
	});

	describe('#initialize', function () {
		var loadStub, parseStub, validateStub, removeStubs;
		beforeEach(function() {
			loadStub = sinon.stub();
			loadStub.displayName = "loadCredentials";

			parseStub = sinon.stub();
			parseStub.displayName = "parseCredentials";

			validateStub = sinon.stub();
			validateStub.displayName = "validateCredentials";

			removeStubs = Connection.__set__({
				"loadCredentials": loadStub,
				"parseCredentials": parseStub,
				"validateCredentials": validateStub,
			});
		});

		afterEach(function() {
			removeStubs();
		});

		it("only loads credentials once", function() {
			loadStub.returns(Q({}));

			var connection = Connection();
			connection.initialize();
			connection.initialize();
			expect(loadStub).to.be.calledOnce;
		});

		describe("with valid credentials", function() {
			var initialization;
			var testOptions = {
				pfx: "myCredentials.pfx", cert: "myCert.pem", key: "myKey.pem", ca: "myCa.pem",
				passphrase: "apntest", production: true
			};

			beforeEach(function() {
				loadStub.withArgs(sinon.match(function(v) {
					return v.pfx == "myCredentials.pfx" && v.cert == "myCert.pem" && v.key == "myKey.pem" &&
						v.ca == "myCa.pem" && v.passphrase == "apntest";
				})).returns(Q({ pfx: "myPfxData", cert: "myCertData", key: "myKeyData", ca: ["myCaData"], passphrase: "apntest" }));

				parseStub.returnsArg(0);

				initialization = Connection(testOptions).initialize();
			});

			it("should be fulfilled", function () {
				return expect(initialization).to.be.fulfilled;
			});

			describe("the validation stage", function() {
				it("is called once", function() {
					return initialization.finally(function() {
						expect(validateStub).to.be.calledOnce;
					});
				});

				it("is passed the production flag", function() {
					return initialization.finally(function() {
						expect(validateStub.getCall(0).args[0]).to.have.property("production", true);
					});
				});

				describe("passed credentials", function() {
					it("contains the PFX data", function() {
						return initialization.finally(function() {
							expect(validateStub.getCall(0).args[0]).to.have.property("pfx", "myPfxData");
						});
					});

					it("contains the key data", function() {
						return initialization.finally(function() {
							expect(validateStub.getCall(0).args[0]).to.have.property("key", "myKeyData");
						});
					});

					it("contains the certificate data", function() {
						return initialization.finally(function() {
							expect(validateStub.getCall(0).args[0]).to.have.property("cert", "myCertData");
						});
					});

					it("includes passphrase", function() {
						return initialization.finally(function() {
							expect(validateStub.getCall(0).args[0]).to.have.property("passphrase", "apntest");
						});
					});
				});
			});

			describe("resolution value", function() {
				it("contains the PFX data", function() {
					return expect(initialization).to.eventually.have.property("pfx", "myPfxData");
				});

				it("contains the key data", function() {
					return expect(initialization).to.eventually.have.property("key", "myKeyData");
				});

				it("contains the certificate data", function() {
					return expect(initialization).to.eventually.have.property("cert", "myCertData");
				});

				it("contains the CA data", function() {
					return expect(initialization).to.eventually.have.deep.property("ca[0]", "myCaData");
				});

				it("includes passphrase", function() {
					return expect(initialization).to.eventually.have.property("passphrase", "apntest");
				});
			});
		});

		describe("credential file cannot be parsed", function() {
			beforeEach(function() {
				loadStub.returns(Q({ cert: "myCertData", key: "myKeyData" }));
				parseStub.throws(new Error("unable to parse key"));
			});

			it("should resolve with the credentials", function() {
				var initialization = Connection({ cert: "myUnparseableCert.pem", key: "myUnparseableKey.pem" }).initialize();
				return expect(initialization).to.become({ cert: "myCertData", key: "myKeyData" });
			});

			it("should log an error", function() {
				var debug = sinon.spy();
				var reset = Connection.__set__("debug", debug);
				var initialization = Connection({ cert: "myUnparseableCert.pem", key: "myUnparseableKey.pem" }).initialize();

				return initialization.finally(function() {
					reset();
					expect(debug).to.be.calledWith(sinon.match(function(err) {
						return err.message ? err.message.match(/unable to parse key/) : false;
					}, "\"unable to parse key\""));
				});
			});

			it("should not attempt to validate", function() {
				var initialization = Connection({ cert: "myUnparseableCert.pem", key: "myUnparseableKey.pem" }).initialize();
				return initialization.finally(function() {
					expect(validateStub).to.not.be.called;
				});
			});
		});

		describe("credential validation fails", function() {
			it("should be rejected", function() {
				loadStub.returns(Q({ cert: "myCertData", key: "myMismatchedKeyData" }));
				parseStub.returnsArg(0);
				validateStub.throws(new Error("certificate and key do not match"));

				var initialization = Connection({ cert: "myCert.pem", key: "myMistmatchedKey.pem" }).initialize();
				return expect(initialization).to.eventually.be.rejectedWith(/certificate and key do not match/);
			});
		});

		describe("credential file cannot be loaded", function() {
			it("should be rejected", function() {
				loadStub.returns(Q.reject(new Error("ENOENT, no such file or directory")));

				var initialization = Connection({ cert: "noSuchFile.pem", key: "myKey.pem" }).initialize();
				return expect(initialization).to.eventually.be.rejectedWith("ENOENT, no such file or directory");
			});
		});
	});

	describe("connect", function() {
		var socketDouble, socketStub, removeSocketStub;

		before(function() {
			var initializeStub = sinon.stub(Connection.prototype, "initialize");
			initializeStub.returns(Q({
				pfx: "pfxData",
				key: "keyData",
				cert: "certData",
				ca: ["caData1", "caData2"],
				passphrase: "apntest" }));
		});

		beforeEach(function() {
			socketDouble = new events.EventEmitter();
			socketDouble.end = sinon.spy();

			socketStub = sinon.stub();
			socketStub.callsArg(2);
			socketStub.returns(socketDouble);

			removeSocketStub = Connection.__set__("createSocket", socketStub);
		});

		afterEach(function() {
			socketDouble.removeAllListeners();
			removeSocketStub();
		});

		it("initializes the module", function(done) {
			var connection = Connection({ pfx: "myCredentials.pfx" });
			return connection.connect().finally(function() {
				expect(connection.initialize).to.have.been.calledOnce;
				done();
			});
		});

		describe("with valid credentials", function() {
			it("resolves", function() {
				var connection = Connection({
					cert: "myCert.pem",
					key: "myKey.pem"
				});
				return expect(connection.connect()).to.be.fulfilled;
			});

			describe("the call to create socket", function() {
				var connect;

				it("passes PFX data", function() {
					connect = Connection({
						pfx: "myCredentials.pfx",
						passphrase: "apntest"
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.pfx).to.equal("pfxData");
					});
				});

				it("passes the passphrase", function() {
					connect = Connection({
						passphrase: "apntest",
						cert: "myCert.pem",
						key: "myKey.pem"
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.passphrase).to.equal("apntest");
					});
				});

				it("passes the cert", function() {
					connect = Connection({
						cert: "myCert.pem",
						key: "myKey.pem"
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.cert).to.equal("certData");
					});
				});

				it("passes the key", function() {
					connect = Connection({
						cert: "test/credentials/support/cert.pem",
						key: "test/credentials/support/key.pem"
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.key).to.equal("keyData");
					});
				});

				it("passes the ca certificates", function() {
					connect = Connection({
						cert: "test/credentials/support/cert.pem",
						key: "test/credentials/support/key.pem",
						ca: [ "test/credentials/support/issuerCert.pem" ]
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.ca[0]).to.equal("caData1");
					});
				});
			});
		});

		describe("intialization failure", function() {
			it("is rejected", function() {
				var connection = Connection({ pfx: "a-non-existant-file-which-really-shouldnt-exist.pfx" });
				connection.on("error", function() {});
				connection.initialize = sinon.stub();

				connection.initialize.returns(Q.reject(new Error("initialize failed")));

				return expect(connection.connect()).to.be.rejectedWith("initialize failed");
			});
		});

		describe("timeout option", function() {
			var clock, timeoutRestore;
			beforeEach(function() {
				clock = sinon.useFakeTimers();
				timeoutRestore = Connection.__set__({
					"setTimeout": clock.setTimeout,
					"clearTimeout": clock.clearTimeout
				});
			});

			afterEach(function() {
				timeoutRestore();
				clock.restore();
			});

			it("ends the socket when connection takes too long", function() {
				var connection = Connection({connectTimeout: 3000}).connect();
				socketStub.onCall(0).returns(socketDouble);

				process.nextTick(function(){
					clock.tick(5000);
				});

				return connection.then(function() {
					throw "connection did not time out";
				}, function() {
					expect(socketDouble.end).to.have.been.called;
				});
			});

			it("does not end the socket when the connnection succeeds", function() {
				var connection = Connection({connectTimeout: 3000}).connect();

				return connection.then(function() {
					clock.tick(5000);
					expect(socketDouble.end).to.not.have.been.called;
				});
			});

			it("does not end the socket when the connection fails", function() {
				var connection = Connection({connectTimeout: 3000}).connect();
				socketStub.onCall(0).returns(socketDouble);

				process.nextTick(function() {
					socketDouble.emit("close");
				});

				return connection.then(function() {
					throw "connection should have failed";
				}, function() {
					clock.tick(5000);
					expect(socketDouble.end).to.not.have.been.called;
				});
			});
		});
	});
});<commit_msg>Process.nextTick is a little too specific<commit_after>var rewire = require("rewire");
var Connection = rewire("../lib/connection");

var events = require("events");
var sinon = require("sinon");
var Q = require("q");

describe("Connection", function() {
	describe('constructor', function () {
		var originalEnv;

		before(function() {
			originalEnv = process.env.NODE_ENV;
		});

		after(function() {
			process.env.NODE_ENV = originalEnv;
		})

		beforeEach(function() {
			process.env.NODE_ENV = "";
		})

		// Issue #50
		it("should use gateway.sandbox.push.apple.com as the default connection address", function () {
			expect(Connection().options.address).to.equal("gateway.sandbox.push.apple.com");
		});

		it("should use gateway.push.apple.com when NODE_ENV=production", function () {
			process.env.NODE_ENV = "production";
			expect(Connection().options.address).to.equal("gateway.push.apple.com");
		});

		it("should give precedence to production flag over NODE_ENV=production", function () {
			process.env.NODE_ENV = "production";
			expect(Connection({ production: false }).options.address).to.equal("gateway.sandbox.push.apple.com");
		});

		it("should use gateway.push.apple.com when production:true", function () {
			expect(Connection({production:true}).options.address).to.equal("gateway.push.apple.com");
		});

		it("should use a custom address when passed", function () {
			expect(Connection({address: "testaddress"}).options.address).to.equal("testaddress");
		});

		describe("address is passed", function() {
			it("sets production to true when using production address", function() {
				expect(Connection({address: "gateway.push.apple.com"}).options.production).to.be.true;
			});

			it("sets production to false when using sandbox address", function() {
				process.env.NODE_ENV = "production";
				expect(Connection({address: "gateway.sandbox.push.apple.com"}).options.production).to.be.false;
			});
		});
	});

	describe('#initialize', function () {
		var loadStub, parseStub, validateStub, removeStubs;
		beforeEach(function() {
			loadStub = sinon.stub();
			loadStub.displayName = "loadCredentials";

			parseStub = sinon.stub();
			parseStub.displayName = "parseCredentials";

			validateStub = sinon.stub();
			validateStub.displayName = "validateCredentials";

			removeStubs = Connection.__set__({
				"loadCredentials": loadStub,
				"parseCredentials": parseStub,
				"validateCredentials": validateStub,
			});
		});

		afterEach(function() {
			removeStubs();
		});

		it("only loads credentials once", function() {
			loadStub.returns(Q({}));

			var connection = Connection();
			connection.initialize();
			connection.initialize();
			expect(loadStub).to.be.calledOnce;
		});

		describe("with valid credentials", function() {
			var initialization;
			var testOptions = {
				pfx: "myCredentials.pfx", cert: "myCert.pem", key: "myKey.pem", ca: "myCa.pem",
				passphrase: "apntest", production: true
			};

			beforeEach(function() {
				loadStub.withArgs(sinon.match(function(v) {
					return v.pfx == "myCredentials.pfx" && v.cert == "myCert.pem" && v.key == "myKey.pem" &&
						v.ca == "myCa.pem" && v.passphrase == "apntest";
				})).returns(Q({ pfx: "myPfxData", cert: "myCertData", key: "myKeyData", ca: ["myCaData"], passphrase: "apntest" }));

				parseStub.returnsArg(0);

				initialization = Connection(testOptions).initialize();
			});

			it("should be fulfilled", function () {
				return expect(initialization).to.be.fulfilled;
			});

			describe("the validation stage", function() {
				it("is called once", function() {
					return initialization.finally(function() {
						expect(validateStub).to.be.calledOnce;
					});
				});

				it("is passed the production flag", function() {
					return initialization.finally(function() {
						expect(validateStub.getCall(0).args[0]).to.have.property("production", true);
					});
				});

				describe("passed credentials", function() {
					it("contains the PFX data", function() {
						return initialization.finally(function() {
							expect(validateStub.getCall(0).args[0]).to.have.property("pfx", "myPfxData");
						});
					});

					it("contains the key data", function() {
						return initialization.finally(function() {
							expect(validateStub.getCall(0).args[0]).to.have.property("key", "myKeyData");
						});
					});

					it("contains the certificate data", function() {
						return initialization.finally(function() {
							expect(validateStub.getCall(0).args[0]).to.have.property("cert", "myCertData");
						});
					});

					it("includes passphrase", function() {
						return initialization.finally(function() {
							expect(validateStub.getCall(0).args[0]).to.have.property("passphrase", "apntest");
						});
					});
				});
			});

			describe("resolution value", function() {
				it("contains the PFX data", function() {
					return expect(initialization).to.eventually.have.property("pfx", "myPfxData");
				});

				it("contains the key data", function() {
					return expect(initialization).to.eventually.have.property("key", "myKeyData");
				});

				it("contains the certificate data", function() {
					return expect(initialization).to.eventually.have.property("cert", "myCertData");
				});

				it("contains the CA data", function() {
					return expect(initialization).to.eventually.have.deep.property("ca[0]", "myCaData");
				});

				it("includes passphrase", function() {
					return expect(initialization).to.eventually.have.property("passphrase", "apntest");
				});
			});
		});

		describe("credential file cannot be parsed", function() {
			beforeEach(function() {
				loadStub.returns(Q({ cert: "myCertData", key: "myKeyData" }));
				parseStub.throws(new Error("unable to parse key"));
			});

			it("should resolve with the credentials", function() {
				var initialization = Connection({ cert: "myUnparseableCert.pem", key: "myUnparseableKey.pem" }).initialize();
				return expect(initialization).to.become({ cert: "myCertData", key: "myKeyData" });
			});

			it("should log an error", function() {
				var debug = sinon.spy();
				var reset = Connection.__set__("debug", debug);
				var initialization = Connection({ cert: "myUnparseableCert.pem", key: "myUnparseableKey.pem" }).initialize();

				return initialization.finally(function() {
					reset();
					expect(debug).to.be.calledWith(sinon.match(function(err) {
						return err.message ? err.message.match(/unable to parse key/) : false;
					}, "\"unable to parse key\""));
				});
			});

			it("should not attempt to validate", function() {
				var initialization = Connection({ cert: "myUnparseableCert.pem", key: "myUnparseableKey.pem" }).initialize();
				return initialization.finally(function() {
					expect(validateStub).to.not.be.called;
				});
			});
		});

		describe("credential validation fails", function() {
			it("should be rejected", function() {
				loadStub.returns(Q({ cert: "myCertData", key: "myMismatchedKeyData" }));
				parseStub.returnsArg(0);
				validateStub.throws(new Error("certificate and key do not match"));

				var initialization = Connection({ cert: "myCert.pem", key: "myMistmatchedKey.pem" }).initialize();
				return expect(initialization).to.eventually.be.rejectedWith(/certificate and key do not match/);
			});
		});

		describe("credential file cannot be loaded", function() {
			it("should be rejected", function() {
				loadStub.returns(Q.reject(new Error("ENOENT, no such file or directory")));

				var initialization = Connection({ cert: "noSuchFile.pem", key: "myKey.pem" }).initialize();
				return expect(initialization).to.eventually.be.rejectedWith("ENOENT, no such file or directory");
			});
		});
	});

	describe("connect", function() {
		var socketDouble, socketStub, removeSocketStub;

		before(function() {
			var initializeStub = sinon.stub(Connection.prototype, "initialize");
			initializeStub.returns(Q({
				pfx: "pfxData",
				key: "keyData",
				cert: "certData",
				ca: ["caData1", "caData2"],
				passphrase: "apntest" }));
		});

		beforeEach(function() {
			socketDouble = new events.EventEmitter();
			socketDouble.end = sinon.spy();

			socketStub = sinon.stub();
			socketStub.callsArg(2);
			socketStub.returns(socketDouble);

			removeSocketStub = Connection.__set__("createSocket", socketStub);
		});

		afterEach(function() {
			socketDouble.removeAllListeners();
			removeSocketStub();
		});

		it("initializes the module", function(done) {
			var connection = Connection({ pfx: "myCredentials.pfx" });
			return connection.connect().finally(function() {
				expect(connection.initialize).to.have.been.calledOnce;
				done();
			});
		});

		describe("with valid credentials", function() {
			it("resolves", function() {
				var connection = Connection({
					cert: "myCert.pem",
					key: "myKey.pem"
				});
				return expect(connection.connect()).to.be.fulfilled;
			});

			describe("the call to create socket", function() {
				var connect;

				it("passes PFX data", function() {
					connect = Connection({
						pfx: "myCredentials.pfx",
						passphrase: "apntest"
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.pfx).to.equal("pfxData");
					});
				});

				it("passes the passphrase", function() {
					connect = Connection({
						passphrase: "apntest",
						cert: "myCert.pem",
						key: "myKey.pem"
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.passphrase).to.equal("apntest");
					});
				});

				it("passes the cert", function() {
					connect = Connection({
						cert: "myCert.pem",
						key: "myKey.pem"
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.cert).to.equal("certData");
					});
				});

				it("passes the key", function() {
					connect = Connection({
						cert: "test/credentials/support/cert.pem",
						key: "test/credentials/support/key.pem"
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.key).to.equal("keyData");
					});
				});

				it("passes the ca certificates", function() {
					connect = Connection({
						cert: "test/credentials/support/cert.pem",
						key: "test/credentials/support/key.pem",
						ca: [ "test/credentials/support/issuerCert.pem" ]
					}).connect();
					return connect.then(function() {
						var socketOptions = socketStub.args[0][1];
						expect(socketOptions.ca[0]).to.equal("caData1");
					});
				});
			});
		});

		describe("intialization failure", function() {
			it("is rejected", function() {
				var connection = Connection({ pfx: "a-non-existant-file-which-really-shouldnt-exist.pfx" });
				connection.on("error", function() {});
				connection.initialize = sinon.stub();

				connection.initialize.returns(Q.reject(new Error("initialize failed")));

				return expect(connection.connect()).to.be.rejectedWith("initialize failed");
			});
		});

		describe("timeout option", function() {
			var clock, timeoutRestore;
			beforeEach(function() {
				clock = sinon.useFakeTimers();
				timeoutRestore = Connection.__set__({
					"setTimeout": clock.setTimeout,
					"clearTimeout": clock.clearTimeout
				});
			});

			afterEach(function() {
				timeoutRestore();
				clock.restore();
			});

			it("ends the socket when connection takes too long", function() {
				var connection = Connection({connectTimeout: 3000}).connect();
				socketStub.onCall(0).returns(socketDouble);

				clock._setTimeout(function() {
					clock.tick(5000);
				}, 1);

				return connection.then(function() {
					throw "connection did not time out";
				}, function() {
					expect(socketDouble.end).to.have.been.called;
				});
			});

			it("does not end the socket when the connnection succeeds", function() {
				var connection = Connection({connectTimeout: 3000}).connect();

				return connection.then(function() {
					clock.tick(5000);
					expect(socketDouble.end).to.not.have.been.called;
				});
			});

			it("does not end the socket when the connection fails", function() {
				var connection = Connection({connectTimeout: 3000}).connect();
				socketStub.onCall(0).returns(socketDouble);

				clock._setTimeout(function() {
					socketDouble.emit("close");
				}, 1);

				return connection.then(function() {
					throw "connection should have failed";
				}, function() {
					clock.tick(5000);
					expect(socketDouble.end).to.not.have.been.called;
				});
			});
		});
	});
});<|endoftext|>