<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;

// MAIN //

/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {string} [options.address] - server address
* @param {string} [options.hostname] - server hostname
* @param {string} [options.latest] - path to the "latest" documentation
* @param {(boolean|string)} [options.logger] - either boolean indicating whether to enable logging or a log level
* @param {NonNegativeInteger} [options.port] - server port
* @param {(string|StringArray)} [options.prefix] - URL path prefix(es) used to create a virtual mount path(s) for static directories
* @param {string} [options.root] - root documentation directory
* @param {(string|StringArray)} [options.static] - path of the directory (or directories) containing static files to serve
* @param {string} [options.template] - application shell template
* @param {ReactComponent} [options.app] - application component
* @param {boolean} [options.trustProxy] - boolean indicating whether to trust `X-forwarded-by` headers when the server is sitting behind a proxy
* @param {boolean} [options.ignoreTrailingSlash] - boolean indicating whether to ignore trailing slashes in routes
* @returns {(Error|null)} error or null
*
* @example
* var options = {
*     'port': 7331,
*     'address': '127.0.0.1'
* };
* var opts = {};
* var err = validate( opts, options );
* if ( err ) {
*     throw err;
* }
*/
function validate( opts, options ) {
	if ( !isObject( options ) ) {
		return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
	}
	if ( hasOwnProp( options, 'address' ) ) {
		opts.address = options.address;
		if ( !isString( opts.address ) ) {
			return new TypeError( 'invalid option. `address` option must be a string. Option: `' + opts.address + '`.' );
		}
	}
	if ( hasOwnProp( options, 'hostname' ) ) {
		opts.hostname = options.hostname;
		if ( !isString( opts.hostname ) ) {
			return new TypeError( 'invalid option. `hostname` option must be a string. Option: `' + opts.hostname + '`.' );
		}
	}
	if ( hasOwnProp( options, 'latest' ) ) {
		opts.latest = options.latest;
		if ( !isString( opts.latest ) ) {
			return new TypeError( 'invalid option. `latest` option must be a string. Option: `' + opts.latest + '`.' );
		}
	}
	if ( hasOwnProp( options, 'logger' ) ) {
		opts.logger = options.logger;
		if ( isString( opts.logger ) ) {
			opts.logger = {
				'level': opts.logger
			};
		} else if ( !isBoolean( opts.logger ) ) {
			return new TypeError( 'invalid option. `logger` option must be either a boolean or a string. Option: `' + opts.logger + '`.' );
		}
	}
	if ( hasOwnProp( options, 'port' ) ) {
		opts.port = options.port;
		if ( !isNonNegativeInteger( opts.port ) ) {
			return new TypeError( 'invalid option. `port` must be a nonnegative integer. Option: `' + opts.port + '`.' );
		}
	}
	if ( hasOwnProp( options, 'prefix' ) ) {
		opts.prefix = options.prefix;
		if ( !isString( opts.prefix ) && !isStringArray( opts.prefix ) ) {
			return new TypeError( 'invalid option. `prefix` option must be either a string or an array of strings. Option: `' + opts.prefix + '`.' );
		}
	}
	if ( hasOwnProp( options, 'root' ) ) {
		opts.root = options.root;
		if ( !isString( opts.root ) ) {
			return new TypeError( 'invalid option. `root` option must be a string. Option: `' + opts.root + '`.' );
		}
	}
	if ( hasOwnProp( options, 'static' ) ) {
		opts.static = options.static;
		if ( !isString( opts.static ) && !isStringArray( opts.static ) ) {
			return new TypeError( 'invalid option. `static` option must be either a string or an array of strings. Option: `' + opts.static + '`.' );
		}
	}
	if ( hasOwnProp( options, 'template' ) ) {
		opts.template = options.template;
		if ( !isString( opts.template ) ) {
			return new TypeError( 'invalid option. `template` option must be a string. Option: `' + opts.template + '`.' );
		}
	}
	if ( hasOwnProp( options, 'app' ) ) {
		opts.app = options.app;
	}
	if ( hasOwnProp( options, 'trustProxy' ) ) {
		opts.trustProxy = options.trustProxy;
		if ( !isBoolean( opts.trustProxy ) ) {
			return new TypeError( 'invalid option. `trustProxy` option must be a boolean. Option: `' + opts.trustProxy + '`.' );
		}
	}
	if ( hasOwnProp( options, 'ignoreTrailingSlash' ) ) {
		opts.ignoreTrailingSlash = options.ignoreTrailingSlash;
		if ( !isBoolean( opts.ignoreTrailingSlash ) ) {
			return new TypeError( 'invalid option. `ignoreTrailingSlash` option must be a boolean. Option: `' + opts.ignoreTrailingSlash + '`.' );
		}
	}
	return null;
}

// EXPORTS //

module.exports = validate;
<commit_msg>Remove options<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;

// MAIN //

/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {string} [options.address] - server address
* @param {string} [options.hostname] - server hostname
* @param {string} [options.latest] - path to the "latest" documentation
* @param {(boolean|string)} [options.logger] - either boolean indicating whether to enable logging or a log level
* @param {NonNegativeInteger} [options.port] - server port
* @param {(string|StringArray)} [options.prefix] - URL path prefix(es) used to create a virtual mount path(s) for static directories
* @param {string} [options.root] - root documentation directory
* @param {(string|StringArray)} [options.static] - path of the directory (or directories) containing static files to serve
* @param {boolean} [options.trustProxy] - boolean indicating whether to trust `X-forwarded-by` headers when the server is sitting behind a proxy
* @param {boolean} [options.ignoreTrailingSlash] - boolean indicating whether to ignore trailing slashes in routes
* @returns {(Error|null)} error or null
*
* @example
* var options = {
*     'port': 7331,
*     'address': '127.0.0.1'
* };
* var opts = {};
* var err = validate( opts, options );
* if ( err ) {
*     throw err;
* }
*/
function validate( opts, options ) {
	if ( !isObject( options ) ) {
		return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
	}
	if ( hasOwnProp( options, 'address' ) ) {
		opts.address = options.address;
		if ( !isString( opts.address ) ) {
			return new TypeError( 'invalid option. `address` option must be a string. Option: `' + opts.address + '`.' );
		}
	}
	if ( hasOwnProp( options, 'hostname' ) ) {
		opts.hostname = options.hostname;
		if ( !isString( opts.hostname ) ) {
			return new TypeError( 'invalid option. `hostname` option must be a string. Option: `' + opts.hostname + '`.' );
		}
	}
	if ( hasOwnProp( options, 'latest' ) ) {
		opts.latest = options.latest;
		if ( !isString( opts.latest ) ) {
			return new TypeError( 'invalid option. `latest` option must be a string. Option: `' + opts.latest + '`.' );
		}
	}
	if ( hasOwnProp( options, 'logger' ) ) {
		opts.logger = options.logger;
		if ( isString( opts.logger ) ) {
			opts.logger = {
				'level': opts.logger
			};
		} else if ( !isBoolean( opts.logger ) ) {
			return new TypeError( 'invalid option. `logger` option must be either a boolean or a string. Option: `' + opts.logger + '`.' );
		}
	}
	if ( hasOwnProp( options, 'port' ) ) {
		opts.port = options.port;
		if ( !isNonNegativeInteger( opts.port ) ) {
			return new TypeError( 'invalid option. `port` must be a nonnegative integer. Option: `' + opts.port + '`.' );
		}
	}
	if ( hasOwnProp( options, 'prefix' ) ) {
		opts.prefix = options.prefix;
		if ( !isString( opts.prefix ) && !isStringArray( opts.prefix ) ) {
			return new TypeError( 'invalid option. `prefix` option must be either a string or an array of strings. Option: `' + opts.prefix + '`.' );
		}
	}
	if ( hasOwnProp( options, 'root' ) ) {
		opts.root = options.root;
		if ( !isString( opts.root ) ) {
			return new TypeError( 'invalid option. `root` option must be a string. Option: `' + opts.root + '`.' );
		}
	}
	if ( hasOwnProp( options, 'static' ) ) {
		opts.static = options.static;
		if ( !isString( opts.static ) && !isStringArray( opts.static ) ) {
			return new TypeError( 'invalid option. `static` option must be either a string or an array of strings. Option: `' + opts.static + '`.' );
		}
	}
	if ( hasOwnProp( options, 'trustProxy' ) ) {
		opts.trustProxy = options.trustProxy;
		if ( !isBoolean( opts.trustProxy ) ) {
			return new TypeError( 'invalid option. `trustProxy` option must be a boolean. Option: `' + opts.trustProxy + '`.' );
		}
	}
	if ( hasOwnProp( options, 'ignoreTrailingSlash' ) ) {
		opts.ignoreTrailingSlash = options.ignoreTrailingSlash;
		if ( !isBoolean( opts.ignoreTrailingSlash ) ) {
			return new TypeError( 'invalid option. `ignoreTrailingSlash` option must be a boolean. Option: `' + opts.ignoreTrailingSlash + '`.' );
		}
	}
	return null;
}

// EXPORTS //

module.exports = validate;
<|endoftext|>


<commit_before>describe('The List Page', () => {
  beforeEach(() => {
    cy.visit('/list.html')
  })

  it('successfully loads', () => {})

  context('navbar', () => {
    it("the 'Home' link works", () => {
      cy.contains('Home').click({force: true})
      cy.title().should('not.equal', 'Error')
    })
    it("the 'About' link works", () => {
      cy.contains('About').click({force: true})
      cy.title().should('not.equal', 'Error')
    })
  })

  context('footer', () => {
    it("the 'MIT License' link works", () => {
      cy.contains('MIT License').click()
    })
    it("the 'CC BY-NC-SA 4.0' link works", () => {
      cy.contains('CC BY-NC-SA 4.0').click()
    })
  })

  context('the list', () => {

    context('location based', () => {
      it("the 'TECH404' link works", () => {
        cy.contains('TECH404').click()
      })
      it("the 'Charleston Tech' link works", () => {
        cy.contains('Charleston Tech').click()
      })
      it("the 'memtech' link works", () => {
        cy.contains('memtech').click()
      })
      it("the 'NashDev' link works", () => {
        cy.contains('NashDev').click()
      })
    })

    context('it based', () => {
      it("the 'APIs You Won't Hate' link works", () => {
        cy.contains('APIs You Won't Hate').click()
      })
    })

    context('programming based', () => {
      it("the 'Larachat' link works", () => {
        cy.contains('Larachat').click()
      })
    })
  })
})<commit_msg>Fix nested quotes<commit_after>describe('The List Page', () => {
  beforeEach(() => {
    cy.visit('/list.html')
  })

  it('successfully loads', () => {})

  context('navbar', () => {
    it("the 'Home' link works", () => {
      cy.contains('Home').click({force: true})
      cy.title().should('not.equal', 'Error')
    })
    it("the 'About' link works", () => {
      cy.contains('About').click({force: true})
      cy.title().should('not.equal', 'Error')
    })
  })

  context('footer', () => {
    it("the 'MIT License' link works", () => {
      cy.contains('MIT License').click()
    })
    it("the 'CC BY-NC-SA 4.0' link works", () => {
      cy.contains('CC BY-NC-SA 4.0').click()
    })
  })

  context('the list', () => {

    context('location based', () => {
      it("the 'TECH404' link works", () => {
        cy.contains('TECH404').click()
      })
      it("the 'Charleston Tech' link works", () => {
        cy.contains('Charleston Tech').click()
      })
      it("the 'memtech' link works", () => {
        cy.contains('memtech').click()
      })
      it("the 'NashDev' link works", () => {
        cy.contains('NashDev').click()
      })
    })

    context('it based', () => {
      it("the 'APIs You Won't Hate' link works", () => {
        cy.contains("APIs You Won't Hate").click()
      })
    })

    context('programming based', () => {
      it("the 'Larachat' link works", () => {
        cy.contains('Larachat').click()
      })
    })
  })
})<|endoftext|>


<commit_before>/*
 * GET home page.
 */
var logger = require('../../log/logger.js').getLogger("uipage");
var fs = require("fs");
var path = require("path");
var hosts = require('hosts-group');
var utils = require('../../utils');
var vhosts = {
	//localConfig: path.resolve(__dirname, '../../../', 'localConfig.json'),
	config: path.resolve(__dirname, '../../../', 'config.json')
};

function getScope(){

	var host = hosts.get();
	var confStr = fs.readFileSync(vhosts.config, 'utf-8');
	var json = JSON.parse(confStr);
	json['hosts'] = host;
	return json;
}

exports.index = function(req, res) {
	res.render('index', {
		title: 'fd-server admin'
	});
};

exports.scope = function(req, res) {
	var data = getScope();
	res.json(data);
};

exports.save = function(req,res){
	var host = hosts.get();
	var data = req.body;
	var olddata = getScope();
	var newdata = utils._.merge(olddata,data);
	fs.writeFileSync(vhosts.config,JSON.stringify(newdata),'utf-8');
	olddata['hosts'] = host;
	res.json(newdata);
};

exports.removeHost = function(req,res){
	var host = hosts.get();
	var domain = req.body.domain;
	var olddata = getScope();
	delete olddata['vhost'][domain];
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.toggleHost = function(req,res){
	var host = hosts.get();
	var domain = req.body.domain;
	var olddata = getScope();
	olddata['vhost'][domain]['status'] = !olddata['vhost'][domain]['status'];
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.removeGroup = function(req,res){
	var host = hosts.get();
	var groupname = req.body.groupname;
	var olddata = getScope();
	olddata['proxyGroup'] = utils._.without(olddata['proxyGroup'],groupname);
	olddata['proxy'] = utils._.filter(olddata['proxy'],function(proxy){
		return proxy.group != groupname;
	});
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.editProxy = function(req,res){
	var pattern = req.body.pattern,
		oldpattern = req.body.oldpattern,
		oldresponder = req.body.oldresponder,
		responder = req.body.responder;
	var host = hosts.get();
	var olddata = getScope();
	var index = utils._.findIndex(olddata['proxy'],function(item){
		return item.pattren == oldpattern && item.responder == oldresponder;
	});
	olddata['proxy'][index]['pattern'] = pattern;
	olddata['proxy'][index]['responder'] = responder;
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.editProxyGroup = function(req,res){
	var oldname = req.body.oldname,
		newname = req.body.newname;
	var host = hosts.get();
	var olddata = getScope();
	olddata['proxyGroup'] = utils._.without(olddata['proxyGroup'],oldname);
	olddata['proxyGroup'].push(newname);
	olddata['proxy'].forEach(function(item,index){
		if(item.group == oldname) {
			olddata['proxy'][index]['group'] = newname;
		}
	});
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.removeProxy = function(req,res){
	var host = hosts.get();
	var pattern = req.body.pattern;
	var responder = req.body.responder;
	var olddata = getScope();
	var index = utils._.findIndex(olddata['proxy'],function(item){
		return item.pattren == oldpattern && item.responder == oldresponder;
	});
	olddata['proxy'].splice(index,1);
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.disabledProxy = function(req,res){
	var host = hosts.get();
	var pattern = req.body.pattern;
	var responder = req.body.responder;
	var olddata = getScope();
	var index = utils._.findIndex(olddata['proxy'],function(item){
		return item.pattren == oldpattern && item.responder == oldresponder;
	});
	olddata['proxy'][index].disabled = req.body.disabled === 'true' ? true : false;
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.onlineProxy = function(req,res){
	var host = hosts.get();
	var openOnlineProxy = req.body.openOnlineProxy;
	var domain = req.body.domain;
	var olddata = getScope();
	olddata['vhost'][domain].openOnlineProxy = parseInt(openOnlineProxy,10);
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};
<commit_msg>fix bugs for proxy parttern<commit_after>/*
 * GET home page.
 */
var logger = require('../../log/logger.js').getLogger("uipage");
var fs = require("fs");
var path = require("path");
var hosts = require('hosts-group');
var utils = require('../../utils');
var vhosts = {
	//localConfig: path.resolve(__dirname, '../../../', 'localConfig.json'),
	config: path.resolve(__dirname, '../../../', 'config.json')
};

function getScope(){

	var host = hosts.get();
	var confStr = fs.readFileSync(vhosts.config, 'utf-8');
	var json = JSON.parse(confStr);
	json['hosts'] = host;
	return json;
}

exports.index = function(req, res) {
	res.render('index', {
		title: 'fd-server admin'
	});
};

exports.scope = function(req, res) {
	var data = getScope();
	res.json(data);
};

exports.save = function(req,res){
	var data = req.body;
	var olddata = getScope();
	var newdata = utils._.merge(olddata,data);
	fs.writeFileSync(vhosts.config,JSON.stringify(newdata),'utf-8');
	res.json(newdata);
};

exports.removeHost = function(req,res){
	var host = hosts.get();
	var domain = req.body.domain;
	var olddata = getScope();
	delete olddata['vhost'][domain];
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.toggleHost = function(req,res){
	var host = hosts.get();
	var domain = req.body.domain;
	var olddata = getScope();
	olddata['vhost'][domain]['status'] = !olddata['vhost'][domain]['status'];
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.removeGroup = function(req,res){
	var groupname = req.body.groupname;
	var olddata = getScope();
	olddata['proxyGroup'] = utils._.without(olddata['proxyGroup'],groupname);
	olddata['proxy'] = utils._.filter(olddata['proxy'],function(proxy){
		return proxy.group != groupname;
	});
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	res.json(olddata);
};

exports.editProxy = function(req,res){
	var pattern = req.body.pattern,
		oldpattern = req.body.oldpattern,
		oldresponder = req.body.oldresponder,
		responder = req.body.responder;
	var olddata = getScope();
	var index = utils._.findIndex(olddata['proxy'],function(item){
		return item.pattern == oldpattern && item.responder == oldresponder;
	});
	logger.info(index);
	olddata['proxy'][index]['pattern'] = pattern;
	olddata['proxy'][index]['responder'] = responder;
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	res.json(olddata);
};

exports.editProxyGroup = function(req,res){
	var oldname = req.body.oldname,
		newname = req.body.newname;
	var olddata = getScope();
	olddata['proxyGroup'] = utils._.without(olddata['proxyGroup'],oldname);
	olddata['proxyGroup'].push(newname);
	olddata['proxy'].forEach(function(item,index){
		if(item.group == oldname) {
			olddata['proxy'][index]['group'] = newname;
		}
	});
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	olddata['hosts'] = host;
	res.json(olddata);
};

exports.removeProxy = function(req,res){
	var host = hosts.get();
	var pattern = req.body.pattern;
	var responder = req.body.responder;
	var olddata = getScope();
	var index = utils._.findIndex(olddata['proxy'],function(item){
		return item.pattern == pattern && item.responder == responder;
	});
	olddata['proxy'].splice(index,1);
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	res.json(olddata);
};

exports.disabledProxy = function(req,res){
	var pattern = req.body.pattern;
	var responder = req.body.responder;
	var olddata = getScope();
	var index = utils._.findIndex(olddata['proxy'],function(item){
		return item.pattern == pattern && item.responder == responder;
	});
	olddata['proxy'][index].disabled = req.body.disabled === 'true' ? true : false;
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	res.json(olddata);
};

exports.onlineProxy = function(req,res){
	var openOnlineProxy = req.body.openOnlineProxy;
	var domain = req.body.domain;
	var olddata = getScope();
	olddata['vhost'][domain].openOnlineProxy = parseInt(openOnlineProxy,10);
	fs.writeFileSync(vhosts.config,JSON.stringify(olddata),'utf-8');
	res.json(olddata);
};
<|endoftext|>


<commit_before>/**
 demo.js
 Copyright (c) 2014 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */

/** Revision of this apps. */
var versionRev = 'V2.1.0 Rev.10';
/** Client ID. */
var currentClientId = null;
/** AccessTonen. */
var accessToken = null;
/** IPアドレスを保持する. */
var ip;
/** 削除モード. */
var deleteMode = false;
/** 画像読み込み中Flag. */
var loadFlag = false;

/** Logメッセージを表示 */
var DEBUG = true;
/** デバイス名をキャッシュ */
var myDeviceName = '';
/** サービス一覧のキャッシュ. */
var cachedServices = [];

/**
 * 初期化処理.
 */
function init() {
  console.log('Origin = [' + location.origin + ']');

  currentClientId = Math.random().toString(36).slice(-8);

  // Versionを表示
  $('#version').html(versionRev);

  // 接続先ipアドレスを取得(指定がない場合は、localhost)
  ip = getIpString();

  // accessTokenをcookieから取得
  accessToken = loadAccessToken();

  // 接続先IPアドレスをページに表示
  $('#host').html('connecting:' + ip);

  // Tokenをページに表示
  $('#token').html('accessToken:' + accessToken);

  showWebSocketState('Closed');

  if (isAndroid() &&
    location.href.indexOf('file:///') == -1) {
      dConnect.setAntiSpoofing(true);
  }
  dConnect.setHost(ip);
  dConnect.setSSLEnabled(location.protocol === 'https:');
  openWebsocketIfNeeded(accessToken);
  searchDevice();
}

function showWebSocketState(state) {
  $('#websocket').html('WebSocket: ' + state);
}

/**
 * Cookieに保存していたアクセストークンを取得する.
 *

 * 注: アクセストークンは本アプリのホスティングされるオリジンごとに作成、保存される.
 *

 * @return アクセストークン. 未保存の場合はnull
 */
function loadAccessToken() {
  return getCookie(accessTokenKey());
}

/**
 * Cookieにアクセストークンを取得する.
 *

 * 注: アクセストークンは本アプリのホスティングされるオリジンごとに作成、保存される.
 *

 * @param accessToken アクセストークン
 */
function storeAccessToken(accessToken) {
  document.cookie = accessTokenKey() + '=' + accessToken;
}

function accessTokenKey() {
  return 'accessToken' + ip + decodeURIComponent(location.origin);
}

/**
 * ユーザエージェントがAndroidであることを確認する.
 */
function isAndroid() {
  var userAgent = window.navigator.userAgent.toLowerCase();
  return (userAgent.indexOf('android') != -1);
}

/**
 * Device Connect Managerを停止後、トップ画面に戻る.
 */
function stopManagerAndDemo() {
  dConnect.stopManager('activity');
  location.hash = '#home';
  if (DEBUG) {
    console.log('URL: ' + location.href);
  }
}

/**
 * Device Connect Managerを起動後、デモ画面に遷移する.
 */
function startManagerAndDemo() {
  $(window).trigger("hashchange");

  startManager(function(apiVersion) {
    if (DEBUG) {
      console.log('Manager has been available already. version=' + apiVersion);
    }
    location.hash = "";
    location.hash = '#demo';
    if (DEBUG) {
      console.log('URL: ' + location.href);
    }
  });
}

var _onWebSocketMessage = function(code, message) {
  console.log('_onWebSocketMessage: code = ' + code + ', message = ' + message);
  var state;
  switch (code) {
    case -1:
      state = 'OK';
      break;
    case 0:
      state = 'Please wait...';
      break;
    case 1:
      state = 'Closed';
      break;
    case 3:
      state = 'Error (AccessToken is required.)';
      break;
    case 4:
      state = 'Error (Origin is not specfied.)';
      break;
    case 5:
      state = 'Please authorize.';
      break;
    default:
      break;
  }
  if (state !== undefined) {
    showWebSocketState(state);
  }
}

function openWebsocketIfNeeded(key) {
  if (!dConnect.isWebSocketReady()) {
    if (dConnect.isConnectedWebSocket()) {
      dConnect.disconnectWebSocket();
    }
    dConnect.setExtendedOrigin("file://");
    dConnect.connectWebSocket(key, _onWebSocketMessage);
    console.log('WebSocket opened.');
  } else {
    console.log('WebSocket is ready.');
  }
}

function reopenWebSocket(key) {
  if (dConnect.isConnectedWebSocket()) {
    dConnect.disconnectWebSocket();
  }
  dConnect.connectWebSocket(key, _onWebSocketMessage);
}

/**
 * Device Connect Managerが起動していることを確認する.
 */
function checkDeviceConnect() {
  startManager(function(apiVersion) {
    alert('Device Connect API version:' + apiVersion);
  });
}

/**
 * Device Connect Managerが起動していることを確認する.
 * @param {function} onavailable
 *                すでに起動していた場合、または起動された場合に呼ばれる関数
 */
function startManager(onavailable) {
  var requested = false;
  var appId = '994422987';
  var errorCallback = function(errorCode, errorMessage) {
    switch (errorCode) {
      case dConnect.constants.ErrorCode.ACCESS_FAILED:
        if (!requested) {
          requested = true;
          dConnect.startManager('activity');
          alert('Requested to start Device Connect Manager.');

          var userAgent = navigator.userAgent.toLowerCase();
          if (userAgent.search(/iphone|ipad|ipod/) > -1) {
            setTimeout(function() {
              location.href = 'itmss://itunes.apple.com/us/app/devicewebapibrowser/id' +
                      appId + '?mt=8&ign-mpt=uo%3D4';
            }, 250);
          }
        }
        setTimeout(function() {
          dConnect.checkDeviceConnect(onavailable, errorCallback);
        }, 500);
        break;
      case dConnect.constants.ErrorCode.INVALID_SERVER:
        alert('WARNING: Device Connect Manager may be spoofed.');
        break;
      case dConnect.constants.ErrorCode.INVALID_ORIGIN:
        alert('WARNING: Origin of this app is invalid. Maybe the origin is not registered in whitelist.');
        break;
      default:
        alert(errorMessage);
        break;
    }
  };

  dConnect.checkDeviceConnect(onavailable, errorCallback);
}

/**
 * Local OAuthのアクセストークンを取得する.
 */
function authorization(callback, oncalcel) {
  var scopes = Array('servicediscovery', 'serviceinformation', 'system',
              'battery', 'connection', 'deviceorientation', 'filedescriptor',
              'file', 'mediaplayer', 'mediastreamrecording', 'notification',
              'phone', 'proximity', 'setting', 'vibration', 'light',
              'remotecontroller', 'drivecontroller', 'mhealth', 'sphero',
              'dice', 'temperature', 'camera', 'canvas', 'health',
              'touch', 'humandetection', 'keyevent', 'omnidirectionalimage',
               'tv', 'powermeter','humidity','illuminance', 'videochat',
               'airconditioner','gpio', 'ecg', 'stressEstimation', 'poseEstimation',
               'walkState', 'messagehook', 'atmosphericPressure', 'geolocation',
               'echonetLite', 'power');
  dConnect.authorization(scopes, 'Demo Web Site',
      function(clientId, newAccessToken) {
        // Client ID
        currentClientId = clientId;

        // accessToken
        accessToken = newAccessToken;

        // debug log
        console.log('accessToken: ' + newAccessToken);

        // add cookie
        storeAccessToken(newAccessToken);

        reopenWebSocket(newAccessToken);

        // rewrite html
        $('#token').html('accessToken:' + newAccessToken);
        if (callback) {
          callback();
        }
      },
      function(errorCode, errorMessage) {
        if (confirm('Failed to get accessToken. Do you try again?')) {
          if (callback) {
            callback();
          }
        } else {
          if (oncalcel) {
            oncalcel();
          }
        }
      });
}

/**
 * 本アプリからリモートアクセスする端末のIPアドレス指定を取得する.
 */
function getIpString() {
  if (1 < document.location.search.length) {
    var query = document.location.search.substring(1);
    var parameters = query.split('&');
    for (var i = 0; i < parameters.length; i++) {
      var element = parameters[i].split('=');
      var paramName = decodeURIComponent(element[0]);
      var paramValue = decodeURIComponent(element[1]);
      if (paramName == 'ip') {
        return paramValue;
      }
    }
  }
  return 'localhost';
}

/**
 * Cookieに保存していた値を取得する.
 *
 * @param {String} name Cookie名
 */
function getCookie(name) {
  var result = null;
  var cookieName = name + '=';
  var allcookies = document.cookie;
  var position = allcookies.indexOf(cookieName);
  if (position != -1) {
    var startIndex = position + cookieName.length;
    var endIndex = allcookies.indexOf(';', startIndex);
    if (endIndex == -1) {
      endIndex = allcookies.length;
    }
    result = decodeURIComponent(allcookies.substring(startIndex, endIndex));
  }
  return result;
}

/**
 * 文字列を比較(大小文字の違いがあっても一致とみなす).
 *
 * @param {String} string 比較する文字列
 * @param {String} cmpString 比較される文字列
 *
 * @return 0以外 一致する
 * @return 0 一致しない
 *
 */
function isEqualToStringIgnoreCase(string, cmpString) {
  return string.toLowerCase() == cmpString.toLowerCase();
}

/**
 * プロファイルごとの分岐.
 *
 * @param {String} serviceId サービスID
 * @param {String} profile プロファイル名
 */
function searchProfile(serviceId, profile) {
  if (isEqualToStringIgnoreCase(profile, dConnect.constants.notification.PROFILE_NAME)) {
    showNotification(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.vibration.PROFILE_NAME)) {
    showVibration(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.media_stream_recording.PROFILE_NAME)) {
    showMediastreamRecording(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.device_orientation.PROFILE_NAME)) {
    showDeviceOrientation(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'drivecontroller')) {
    showDriveController(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'remotecontroller')) {
    showRemoteController(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.file.PROFILE_NAME)) {
    showFile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'light')) {
    showSearchLight(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.phone.PROFILE_NAME)) {
    showPhone(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.connection.PROFILE_NAME)) {
    showConnection(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.setting.PROFILE_NAME)) {
    showSetting(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.media_player.PROFILE_NAME)) {
    showMediaPlayer(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.battery.PROFILE_NAME)) {
    showBattery(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'camera')) {
    showCamera(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'dice')) {
    showDice(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'mhealth')) {
    showMhealth(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'temperature')) {
    showTemperatureProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.proximity.PROFILE_NAME)) {
    showProximity(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'sphero')) {
    showSphero(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.canvas.PROFILE_NAME)) {
    showCanvas(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'health')) {
    showHealth(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.touch.PROFILE_NAME)) {
    showTouch(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'humandetection')) {
    showHumanDetection(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.keyevent.PROFILE_NAME)) {
    showKeyEvent(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'videochat')) {
    showVideoChat(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'omnidirectionalimage')) {
    showOmnidirectionalImage(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.serviceinformation.PROFILE_NAME)) {
    showServiceInformation(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'humidity')) {
    showHumidity(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'illuminance')) {
    showIlluminance(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'powermeter')) {
    showPowerMeter(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'tv')) {
    showTV(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'airconditioner')) {
    showAirConditioner(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'gpio')) {
    showGPIO(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'ecg')) {
    showECGProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'stressEstimation')) {
    showStressEstimationProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'poseEstimation')) {
    showPoseEstimationProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'walkState')) {
    showWalkStateProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'messagehook')) {
    showMessageHook(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'atmosphericPressure')) {
    showAtmosphericPressure(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'geolocation')) {
    showGeolocation(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'power')) {
    showPower(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'echonetLite')) {
    showECHONETLite(serviceId);
  }
}
<commit_msg>localの判定を追加。<commit_after>/**
 demo.js
 Copyright (c) 2014 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */

/** Revision of this apps. */
var versionRev = 'V2.1.0 Rev.10';
/** Client ID. */
var currentClientId = null;
/** AccessTonen. */
var accessToken = null;
/** IPアドレスを保持する. */
var ip;
/** 削除モード. */
var deleteMode = false;
/** 画像読み込み中Flag. */
var loadFlag = false;

/** Logメッセージを表示 */
var DEBUG = true;
/** デバイス名をキャッシュ */
var myDeviceName = '';
/** サービス一覧のキャッシュ. */
var cachedServices = [];

/**
 * 初期化処理.
 */
function init() {
  console.log('Origin = [' + location.origin + ']');

  currentClientId = Math.random().toString(36).slice(-8);

  // Versionを表示
  $('#version').html(versionRev);

  // 接続先ipアドレスを取得(指定がない場合は、localhost)
  ip = getIpString();

  // accessTokenをcookieから取得
  accessToken = loadAccessToken();

  // 接続先IPアドレスをページに表示
  $('#host').html('connecting:' + ip);

  // Tokenをページに表示
  $('#token').html('accessToken:' + accessToken);

  showWebSocketState('Closed');

  if (isAndroid() &&
    location.href.indexOf('file:///') == -1) {
      dConnect.setAntiSpoofing(true);
  }
  dConnect.setHost(ip);
  dConnect.setSSLEnabled(location.protocol === 'https:');
  openWebsocketIfNeeded(accessToken);
  searchDevice();
}

function showWebSocketState(state) {
  $('#websocket').html('WebSocket: ' + state);
}

/**
 * Cookieに保存していたアクセストークンを取得する.
 *

 * 注: アクセストークンは本アプリのホスティングされるオリジンごとに作成、保存される.
 *

 * @return アクセストークン. 未保存の場合はnull
 */
function loadAccessToken() {
  return getCookie(accessTokenKey());
}

/**
 * Cookieにアクセストークンを取得する.
 *

 * 注: アクセストークンは本アプリのホスティングされるオリジンごとに作成、保存される.
 *

 * @param accessToken アクセストークン
 */
function storeAccessToken(accessToken) {
  document.cookie = accessTokenKey() + '=' + accessToken;
}

function accessTokenKey() {
  return 'accessToken' + ip + decodeURIComponent(location.origin);
}

/**
 * ユーザエージェントがAndroidであることを確認する.
 */
function isAndroid() {
  var userAgent = window.navigator.userAgent.toLowerCase();
  return (userAgent.indexOf('android') != -1);
}

/**
 * Device Connect Managerを停止後、トップ画面に戻る.
 */
function stopManagerAndDemo() {
  dConnect.stopManager('activity');
  location.hash = '#home';
  if (DEBUG) {
    console.log('URL: ' + location.href);
  }
}

/**
 * Device Connect Managerを起動後、デモ画面に遷移する.
 */
function startManagerAndDemo() {
  $(window).trigger("hashchange");

  startManager(function(apiVersion) {
    if (DEBUG) {
      console.log('Manager has been available already. version=' + apiVersion);
    }
    location.hash = "";
    location.hash = '#demo';
    if (DEBUG) {
      console.log('URL: ' + location.href);
    }
  });
}

var _onWebSocketMessage = function(code, message) {
  console.log('_onWebSocketMessage: code = ' + code + ', message = ' + message);
  var state;
  switch (code) {
    case -1:
      state = 'OK';
      break;
    case 0:
      state = 'Please wait...';
      break;
    case 1:
      state = 'Closed';
      break;
    case 3:
      state = 'Error (AccessToken is required.)';
      break;
    case 4:
      state = 'Error (Origin is not specfied.)';
      break;
    case 5:
      state = 'Please authorize.';
      break;
    default:
      break;
  }
  if (state !== undefined) {
    showWebSocketState(state);
  }
}

function openWebsocketIfNeeded(key) {
  if (!dConnect.isWebSocketReady()) {
    if (dConnect.isConnectedWebSocket()) {
      dConnect.disconnectWebSocket();
    }
    if (location.origin == 'file://') {
      dConnect.setExtendedOrigin("file://");
    }
    dConnect.connectWebSocket(key, _onWebSocketMessage);
    console.log('WebSocket opened.');
  } else {
    console.log('WebSocket is ready.');
  }
}

function reopenWebSocket(key) {
  if (dConnect.isConnectedWebSocket()) {
    dConnect.disconnectWebSocket();
  }
  dConnect.connectWebSocket(key, _onWebSocketMessage);
}

/**
 * Device Connect Managerが起動していることを確認する.
 */
function checkDeviceConnect() {
  startManager(function(apiVersion) {
    alert('Device Connect API version:' + apiVersion);
  });
}

/**
 * Device Connect Managerが起動していることを確認する.
 * @param {function} onavailable
 *                すでに起動していた場合、または起動された場合に呼ばれる関数
 */
function startManager(onavailable) {
  var requested = false;
  var appId = '994422987';
  var errorCallback = function(errorCode, errorMessage) {
    switch (errorCode) {
      case dConnect.constants.ErrorCode.ACCESS_FAILED:
        if (!requested) {
          requested = true;
          dConnect.startManager('activity');
          alert('Requested to start Device Connect Manager.');

          var userAgent = navigator.userAgent.toLowerCase();
          if (userAgent.search(/iphone|ipad|ipod/) > -1) {
            setTimeout(function() {
              location.href = 'itmss://itunes.apple.com/us/app/devicewebapibrowser/id' +
                      appId + '?mt=8&ign-mpt=uo%3D4';
            }, 250);
          }
        }
        setTimeout(function() {
          dConnect.checkDeviceConnect(onavailable, errorCallback);
        }, 500);
        break;
      case dConnect.constants.ErrorCode.INVALID_SERVER:
        alert('WARNING: Device Connect Manager may be spoofed.');
        break;
      case dConnect.constants.ErrorCode.INVALID_ORIGIN:
        alert('WARNING: Origin of this app is invalid. Maybe the origin is not registered in whitelist.');
        break;
      default:
        alert(errorMessage);
        break;
    }
  };

  dConnect.checkDeviceConnect(onavailable, errorCallback);
}

/**
 * Local OAuthのアクセストークンを取得する.
 */
function authorization(callback, oncalcel) {
  var scopes = Array('servicediscovery', 'serviceinformation', 'system',
              'battery', 'connection', 'deviceorientation', 'filedescriptor',
              'file', 'mediaplayer', 'mediastreamrecording', 'notification',
              'phone', 'proximity', 'setting', 'vibration', 'light',
              'remotecontroller', 'drivecontroller', 'mhealth', 'sphero',
              'dice', 'temperature', 'camera', 'canvas', 'health',
              'touch', 'humandetection', 'keyevent', 'omnidirectionalimage',
               'tv', 'powermeter','humidity','illuminance', 'videochat',
               'airconditioner','gpio', 'ecg', 'stressEstimation', 'poseEstimation',
               'walkState', 'messagehook', 'atmosphericPressure', 'geolocation',
               'echonetLite', 'power');
  dConnect.authorization(scopes, 'Demo Web Site',
      function(clientId, newAccessToken) {
        // Client ID
        currentClientId = clientId;

        // accessToken
        accessToken = newAccessToken;

        // debug log
        console.log('accessToken: ' + newAccessToken);

        // add cookie
        storeAccessToken(newAccessToken);

        reopenWebSocket(newAccessToken);

        // rewrite html
        $('#token').html('accessToken:' + newAccessToken);
        if (callback) {
          callback();
        }
      },
      function(errorCode, errorMessage) {
        if (confirm('Failed to get accessToken. Do you try again?')) {
          if (callback) {
            callback();
          }
        } else {
          if (oncalcel) {
            oncalcel();
          }
        }
      });
}

/**
 * 本アプリからリモートアクセスする端末のIPアドレス指定を取得する.
 */
function getIpString() {
  if (1 < document.location.search.length) {
    var query = document.location.search.substring(1);
    var parameters = query.split('&');
    for (var i = 0; i < parameters.length; i++) {
      var element = parameters[i].split('=');
      var paramName = decodeURIComponent(element[0]);
      var paramValue = decodeURIComponent(element[1]);
      if (paramName == 'ip') {
        return paramValue;
      }
    }
  }
  return 'localhost';
}

/**
 * Cookieに保存していた値を取得する.
 *
 * @param {String} name Cookie名
 */
function getCookie(name) {
  var result = null;
  var cookieName = name + '=';
  var allcookies = document.cookie;
  var position = allcookies.indexOf(cookieName);
  if (position != -1) {
    var startIndex = position + cookieName.length;
    var endIndex = allcookies.indexOf(';', startIndex);
    if (endIndex == -1) {
      endIndex = allcookies.length;
    }
    result = decodeURIComponent(allcookies.substring(startIndex, endIndex));
  }
  return result;
}

/**
 * 文字列を比較(大小文字の違いがあっても一致とみなす).
 *
 * @param {String} string 比較する文字列
 * @param {String} cmpString 比較される文字列
 *
 * @return 0以外 一致する
 * @return 0 一致しない
 *
 */
function isEqualToStringIgnoreCase(string, cmpString) {
  return string.toLowerCase() == cmpString.toLowerCase();
}

/**
 * プロファイルごとの分岐.
 *
 * @param {String} serviceId サービスID
 * @param {String} profile プロファイル名
 */
function searchProfile(serviceId, profile) {
  if (isEqualToStringIgnoreCase(profile, dConnect.constants.notification.PROFILE_NAME)) {
    showNotification(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.vibration.PROFILE_NAME)) {
    showVibration(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.media_stream_recording.PROFILE_NAME)) {
    showMediastreamRecording(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.device_orientation.PROFILE_NAME)) {
    showDeviceOrientation(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'drivecontroller')) {
    showDriveController(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'remotecontroller')) {
    showRemoteController(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.file.PROFILE_NAME)) {
    showFile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'light')) {
    showSearchLight(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.phone.PROFILE_NAME)) {
    showPhone(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.connection.PROFILE_NAME)) {
    showConnection(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.setting.PROFILE_NAME)) {
    showSetting(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.media_player.PROFILE_NAME)) {
    showMediaPlayer(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.battery.PROFILE_NAME)) {
    showBattery(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'camera')) {
    showCamera(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'dice')) {
    showDice(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'mhealth')) {
    showMhealth(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'temperature')) {
    showTemperatureProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.proximity.PROFILE_NAME)) {
    showProximity(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'sphero')) {
    showSphero(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.canvas.PROFILE_NAME)) {
    showCanvas(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'health')) {
    showHealth(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.touch.PROFILE_NAME)) {
    showTouch(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'humandetection')) {
    showHumanDetection(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.keyevent.PROFILE_NAME)) {
    showKeyEvent(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'videochat')) {
    showVideoChat(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'omnidirectionalimage')) {
    showOmnidirectionalImage(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, dConnect.constants.serviceinformation.PROFILE_NAME)) {
    showServiceInformation(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'humidity')) {
    showHumidity(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'illuminance')) {
    showIlluminance(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'powermeter')) {
    showPowerMeter(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'tv')) {
    showTV(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'airconditioner')) {
    showAirConditioner(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'gpio')) {
    showGPIO(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'ecg')) {
    showECGProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'stressEstimation')) {
    showStressEstimationProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'poseEstimation')) {
    showPoseEstimationProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'walkState')) {
    showWalkStateProfile(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'messagehook')) {
    showMessageHook(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'atmosphericPressure')) {
    showAtmosphericPressure(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'geolocation')) {
    showGeolocation(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'power')) {
    showPower(serviceId);
  } else if (isEqualToStringIgnoreCase(profile, 'echonetLite')) {
    showECHONETLite(serviceId);
  }
}
<|endoftext|>


<commit_before>
const traverse = require('traverse');
const checkContext = require('./check-context');

module.exports = function mongoKeys (ObjectID, keyFields) {
  keyFields = Array.isArray(keyFields) ? keyFields : [keyFields];
  const keyLeaves = [];

  const keysInfo = keyFields.map(field => {
    const fieldNames = field.split('.');
    const leaf = fieldNames.slice(-1)[0];
    keyLeaves.push(leaf);

    return { leaf, len: fieldNames.length, path: JSON.stringify(fieldNames) };
  });

  return context => {
    checkContext(context, 'before', ['find', 'update', 'patch', 'remove'], 'mongoKeys');
    const query = context.params.query || {};

    traverse(query).forEach(function (node) {
      const typeofNode = typeof node;
      const key = this.key;
      const path = this.path;

      if (keyLeaves.indexOf(key) === -1) return;
      if (path.indexOf('$sort') !== -1) return;

      keysInfo.forEach(info => {
        if (info.leaf === key && info.len <= path.length) {
          const endPath = path.slice(-info.len);
          if (JSON.stringify(endPath) === info.path) {
            if (typeofNode === 'object' && node !== null && !Array.isArray(node)) {
              // { keyPath: { ... } }
              const actualProps = Object.keys(node);
              const onlyProp = actualProps[0];

              if (actualProps.length === 1 && onlyProp === '$in') {
                // { keyPath: { $in: [...] } }
                const newNode = { $in: wrapValue(node[onlyProp], true) };
                this.update(newNode);
              }
            } else if (typeofNode === 'string' || typeofNode === 'number') {
              // { keyPath: '111111111111' }
              const newNode = wrapValue(node, true);
              this.update(newNode);
            }
          }
        }
      });
    });

    return context;
  };

  function wrapValue (value) {
    return Array.isArray(value) ? value.map(val => new ObjectID(val)) : new ObjectID(value);
  }
};
<commit_msg>allow mongoKeys running for all methods<commit_after>
const traverse = require('traverse');
const checkContext = require('./check-context');

module.exports = function mongoKeys (ObjectID, keyFields) {
  keyFields = Array.isArray(keyFields) ? keyFields : [keyFields];
  const keyLeaves = [];

  const keysInfo = keyFields.map(field => {
    const fieldNames = field.split('.');
    const leaf = fieldNames.slice(-1)[0];
    keyLeaves.push(leaf);

    return { leaf, len: fieldNames.length, path: JSON.stringify(fieldNames) };
  });

  return context => {
    checkContext(context, 'before', null, 'mongoKeys');
    const query = context.params.query || {};

    traverse(query).forEach(function (node) {
      const typeofNode = typeof node;
      const key = this.key;
      const path = this.path;

      if (keyLeaves.indexOf(key) === -1) return;
      if (path.indexOf('$sort') !== -1) return;

      keysInfo.forEach(info => {
        if (info.leaf === key && info.len <= path.length) {
          const endPath = path.slice(-info.len);
          if (JSON.stringify(endPath) === info.path) {
            if (typeofNode === 'object' && node !== null && !Array.isArray(node)) {
              // { keyPath: { ... } }
              const actualProps = Object.keys(node);
              const onlyProp = actualProps[0];

              if (actualProps.length === 1 && onlyProp === '$in') {
                // { keyPath: { $in: [...] } }
                const newNode = { $in: wrapValue(node[onlyProp], true) };
                this.update(newNode);
              }
            } else if (typeofNode === 'string' || typeofNode === 'number') {
              // { keyPath: '111111111111' }
              const newNode = wrapValue(node, true);
              this.update(newNode);
            }
          }
        }
      });
    });

    return context;
  };

  function wrapValue (value) {
    return Array.isArray(value) ? value.map(val => new ObjectID(val)) : new ObjectID(value);
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-iotagent-lib
 *
 * fiware-iotagent-lib 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.
 *
 * fiware-iotagent-lib 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 fiware-iotagent-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

var async = require('async'),
    errors = require('../errors'),
    logger = require('logops'),
    context = {
        op: 'IoTAgentNGSI.NGSIParser'
    },
    DOMParser = require('xmldom').DOMParser;

function extractElementData(entityIdNode, callback) {
    var elementData = {},
        idNodes = entityIdNode.getElementsByTagName('id');

    if (!idNodes || idNodes.length !== 1) {
        callback(new errors.BadRequest('Error parsing XML: context id not found'));
        return;
    }

    elementData.id = idNodes.item(0).firstChild.nodeValue;
    elementData.type = entityIdNode.getAttribute('type');
    elementData.isPattern = entityIdNode.getAttribute('isPattern');

    callback(null, elementData);
}

function extractElementAttributes(attributeList, callback) {
    var attributes = [];

    for (var q = 0; q < attributeList.length; q++) {
        var attribute = {},
            attributeNames = attributeList.item(q).getElementsByTagName('name'),
            attributeTypes = attributeList.item(q).getElementsByTagName('type'),
            attributeValues = attributeList.item(q).getElementsByTagName('contextValue');

        if (attributeNames.length === 1) {
            attribute.name = attributeNames.item(0).firstChild.nodeValue;
        }

        if (attributeTypes.length === 1) {
            attribute.type = attributeTypes.item(0).firstChild.nodeValue;
        }

        if (attributeValues.length === 1) {
            attribute.value = attributeValues.item(0).firstChild.nodeValue;
        }

        attributes.push(attribute);
    }

    callback(null, attributes);
}

function extractNode(node, callback) {
    var attributeList = node.getElementsByTagName('contextAttribute'),
        entityIdNodes = node.getElementsByTagName('entityId');

    if (!entityIdNodes || entityIdNodes.length !== 1) {
        callback(new errors.BadRequest('Error parsing XML: context element not found'));
        return;
    }

    async.parallel([
        async.apply(extractElementData, entityIdNodes.item(0)),
        async.apply(extractElementAttributes, attributeList)
    ], function combineExtractedData(error, results) {
        if (error) {
            callback(error);
        } else {
            var contextElement = results[0];

            contextElement.attributes = results[1];
            callback(null, contextElement);
        }
    });
}

function readUpdatePayload(req, callback) {
    var doc = new DOMParser().parseFromString(req.rawBody);

    function extractUpdateAction(doc, callback) {
        var updateActionNodes = doc.getElementsByTagName('updateAction');

        if (updateActionNodes.length !== 1) {
            callback(new errors.BadRequest('Error parsing XML: update action element not found'));
            return;
        }

        callback(null, updateActionNodes.item(0).firstChild.nodeValue);
    }

    function extractContextElements(doc, callback) {
        var contextElementList = doc.getElementsByTagName('contextElement'),
            contextElements = [];

        for (var i = 0; i < contextElementList.length; i++) {
            contextElements.push(contextElementList.item(i));
        }

        async.map(contextElements, extractNode, callback);
    }

    function createUpdateBody(error, results) {
        if (error) {
            logger.debug(context, 'Error parsing XML Update Context body: %s', error);

            callback(error);
        } else {
            var element = {
                contextElements: results[1],
                updateAction: results[0]
            };

            req.body = element;
            callback(null, element);
        }
    }

    async.series([
        async.apply(extractUpdateAction, doc),
        async.apply(extractContextElements, doc)
    ], createUpdateBody);
}

function readQueryPayload(req, callback) {
    var doc = new DOMParser().parseFromString(req.rawBody);

    function extractEntities(doc, callback) {
        var entityElementList = doc.getElementsByTagName('entityId'),
            entityElements = [];

        for (var i = 0; i < entityElementList.length; i++) {
            entityElements.push(entityElementList.item(i));
        }

        async.map(entityElements, extractElementData, callback);
    }

    function extractAttributes(doc, callback) {
        var attributeList = doc.getElementsByTagName('attribute'),
            attributes = [];

        for (var i = 0; i < attributeList.length; i++) {
            attributes.push(attributeList.item(i).firstChild.nodeValue);
        }

        callback(null, attributes);
    }

    function createQueryBody(error, results) {
        if (error) {
            logger.debug(context, 'Error parsing XML Query Context body: %s', error);
            callback(error);
        } else {
            var element = {
                entities: results[0],
                attributes: results[1]
            };

            req.body = element;
            callback(null, element);
        }
    }

    async.series([
        async.apply(extractEntities, doc),
        async.apply(extractAttributes, doc)
    ], createQueryBody);
}

function readBody(parseFunction) {
    return function readMiddleware(req, res, next) {
        if (req.headers['content-type'] === 'application/xml') {
            parseFunction(req, next);
        } else {
            next();
        }
    };
}

/**
 * Given a NGSI Body, determines whether it contains any NGSI error.
 *
 * @param {String} body             String representing a NGSI body in JSON format.
 * @return {Number|*}
 */
function getErrorField(body) {
    var errorField = body.errorCode ||
        body.orionError;

    if (body && body.contextResponses) {
        for (var i in body.contextResponses) {
            if (body.contextResponses[i] && body.contextResponses[i] &&
                body.contextResponses[i].statusCode && body.contextResponses[i].statusCode.code !== '200') {
                errorField = body.contextResponses[i].statusCode;
            }
        }
    }

    return errorField;
}

exports.readUpdateBody = readBody(readUpdatePayload);
exports.readQueryBody = readBody(readQueryPayload);
exports.getErrorField = getErrorField;
<commit_msg>FIX Remove double check<commit_after>/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-iotagent-lib
 *
 * fiware-iotagent-lib 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.
 *
 * fiware-iotagent-lib 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 fiware-iotagent-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

var async = require('async'),
    errors = require('../errors'),
    logger = require('logops'),
    context = {
        op: 'IoTAgentNGSI.NGSIParser'
    },
    DOMParser = require('xmldom').DOMParser;

function extractElementData(entityIdNode, callback) {
    var elementData = {},
        idNodes = entityIdNode.getElementsByTagName('id');

    if (!idNodes || idNodes.length !== 1) {
        callback(new errors.BadRequest('Error parsing XML: context id not found'));
        return;
    }

    elementData.id = idNodes.item(0).firstChild.nodeValue;
    elementData.type = entityIdNode.getAttribute('type');
    elementData.isPattern = entityIdNode.getAttribute('isPattern');

    callback(null, elementData);
}

function extractElementAttributes(attributeList, callback) {
    var attributes = [];

    for (var q = 0; q < attributeList.length; q++) {
        var attribute = {},
            attributeNames = attributeList.item(q).getElementsByTagName('name'),
            attributeTypes = attributeList.item(q).getElementsByTagName('type'),
            attributeValues = attributeList.item(q).getElementsByTagName('contextValue');

        if (attributeNames.length === 1) {
            attribute.name = attributeNames.item(0).firstChild.nodeValue;
        }

        if (attributeTypes.length === 1) {
            attribute.type = attributeTypes.item(0).firstChild.nodeValue;
        }

        if (attributeValues.length === 1) {
            attribute.value = attributeValues.item(0).firstChild.nodeValue;
        }

        attributes.push(attribute);
    }

    callback(null, attributes);
}

function extractNode(node, callback) {
    var attributeList = node.getElementsByTagName('contextAttribute'),
        entityIdNodes = node.getElementsByTagName('entityId');

    if (!entityIdNodes || entityIdNodes.length !== 1) {
        callback(new errors.BadRequest('Error parsing XML: context element not found'));
        return;
    }

    async.parallel([
        async.apply(extractElementData, entityIdNodes.item(0)),
        async.apply(extractElementAttributes, attributeList)
    ], function combineExtractedData(error, results) {
        if (error) {
            callback(error);
        } else {
            var contextElement = results[0];

            contextElement.attributes = results[1];
            callback(null, contextElement);
        }
    });
}

function readUpdatePayload(req, callback) {
    var doc = new DOMParser().parseFromString(req.rawBody);

    function extractUpdateAction(doc, callback) {
        var updateActionNodes = doc.getElementsByTagName('updateAction');

        if (updateActionNodes.length !== 1) {
            callback(new errors.BadRequest('Error parsing XML: update action element not found'));
            return;
        }

        callback(null, updateActionNodes.item(0).firstChild.nodeValue);
    }

    function extractContextElements(doc, callback) {
        var contextElementList = doc.getElementsByTagName('contextElement'),
            contextElements = [];

        for (var i = 0; i < contextElementList.length; i++) {
            contextElements.push(contextElementList.item(i));
        }

        async.map(contextElements, extractNode, callback);
    }

    function createUpdateBody(error, results) {
        if (error) {
            logger.debug(context, 'Error parsing XML Update Context body: %s', error);

            callback(error);
        } else {
            var element = {
                contextElements: results[1],
                updateAction: results[0]
            };

            req.body = element;
            callback(null, element);
        }
    }

    async.series([
        async.apply(extractUpdateAction, doc),
        async.apply(extractContextElements, doc)
    ], createUpdateBody);
}

function readQueryPayload(req, callback) {
    var doc = new DOMParser().parseFromString(req.rawBody);

    function extractEntities(doc, callback) {
        var entityElementList = doc.getElementsByTagName('entityId'),
            entityElements = [];

        for (var i = 0; i < entityElementList.length; i++) {
            entityElements.push(entityElementList.item(i));
        }

        async.map(entityElements, extractElementData, callback);
    }

    function extractAttributes(doc, callback) {
        var attributeList = doc.getElementsByTagName('attribute'),
            attributes = [];

        for (var i = 0; i < attributeList.length; i++) {
            attributes.push(attributeList.item(i).firstChild.nodeValue);
        }

        callback(null, attributes);
    }

    function createQueryBody(error, results) {
        if (error) {
            logger.debug(context, 'Error parsing XML Query Context body: %s', error);
            callback(error);
        } else {
            var element = {
                entities: results[0],
                attributes: results[1]
            };

            req.body = element;
            callback(null, element);
        }
    }

    async.series([
        async.apply(extractEntities, doc),
        async.apply(extractAttributes, doc)
    ], createQueryBody);
}

function readBody(parseFunction) {
    return function readMiddleware(req, res, next) {
        if (req.headers['content-type'] === 'application/xml') {
            parseFunction(req, next);
        } else {
            next();
        }
    };
}

/**
 * Given a NGSI Body, determines whether it contains any NGSI error.
 *
 * @param {String} body             String representing a NGSI body in JSON format.
 * @return {Number|*}
 */
function getErrorField(body) {
    var errorField = body.errorCode ||
        body.orionError;

    if (body && body.contextResponses) {
        for (var i in body.contextResponses) {
            if (body.contextResponses[i].statusCode && body.contextResponses[i].statusCode.code !== '200') {
                errorField = body.contextResponses[i].statusCode;
            }
        }
    }

    return errorField;
}

exports.readUpdateBody = readBody(readUpdatePayload);
exports.readQueryBody = readBody(readQueryPayload);
exports.getErrorField = getErrorField;
<|endoftext|>


<commit_before>context('Form', () => {
	before(() => {
		cy.login();
		cy.visit('/desk#workspace/Website');
		cy.window().its('frappe').then(frappe => {
			frappe.call("frappe.tests.ui_test_helpers.create_contact_records");
		});
	});
	beforeEach(() => {
		cy.visit('/desk#workspace/Website');
	});
	it('create a new form', () => {
		cy.visit('/desk#Form/ToDo/New ToDo 1');
		cy.fill_field('description', 'this is a test todo', 'Text Editor').blur();
		cy.get('.page-title').should('contain', 'Not Saved');
		cy.get('.primary-action').click();
		cy.visit('/desk#List/ToDo');
		cy.location('hash').should('eq', '#List/ToDo/List');
		cy.get('h1').should('be.visible').and('contain', 'To Do');
		cy.get('.list-row').should('contain', 'this is a test todo');
	});
	it('navigates between documents with child table list filters applied', () => {
		cy.visit('/desk#List/Contact');
		cy.location('hash').should('eq', '#List/Contact/List');
		cy.get('.tag-filters-area .btn:contains("Add Filter")').click();
		cy.get('.fieldname-select-area').should('exist');
		cy.get('.fieldname-select-area input').type('Number{enter}', { force: true });
		cy.get('.filter-field .input-with-feedback.form-control').type('123', { force: true });
		cy.get('.filter-box .btn:contains("Apply")').click({ force: true });
		cy.visit('/desk#Form/Contact/Test Form Contact 3');
		cy.get('.prev-doc').should('be.visible').click();
		cy.get('.msgprint-dialog .modal-body').contains('No further records').should('be.visible');
		cy.get('.btn-modal-close:visible').click();
		cy.get('.next-doc').click();
		cy.wait(200);
		cy.contains('Test Form Contact 2').should('not.exist');
		cy.get('.page-title .title-text').should('contain', 'Test Form Contact 1');
		// clear filters
		cy.window().its('frappe').then((frappe) => {
			let list_view = frappe.get_list_view('Contact');
			list_view.filter_area.filter_list.clear_filters();
		});
	});
});
<commit_msg>refactor: return promise explicitly<commit_after>context('Form', () => {
	before(() => {
		cy.login();
		cy.visit('/desk#workspace/Website');
		return cy.window().its('frappe').then(frappe => {
			return frappe.call("frappe.tests.ui_test_helpers.create_contact_records");
		});
	});
	beforeEach(() => {
		cy.visit('/desk#workspace/Website');
	});
	it('create a new form', () => {
		cy.visit('/desk#Form/ToDo/New ToDo 1');
		cy.fill_field('description', 'this is a test todo', 'Text Editor').blur();
		cy.get('.page-title').should('contain', 'Not Saved');
		cy.get('.primary-action').click();
		cy.visit('/desk#List/ToDo');
		cy.location('hash').should('eq', '#List/ToDo/List');
		cy.get('h1').should('be.visible').and('contain', 'To Do');
		cy.get('.list-row').should('contain', 'this is a test todo');
	});
	it('navigates between documents with child table list filters applied', () => {
		cy.visit('/desk#List/Contact');
		cy.location('hash').should('eq', '#List/Contact/List');
		cy.get('.tag-filters-area .btn:contains("Add Filter")').click();
		cy.get('.fieldname-select-area').should('exist');
		cy.get('.fieldname-select-area input').type('Number{enter}', { force: true });
		cy.get('.filter-field .input-with-feedback.form-control').type('123', { force: true });
		cy.get('.filter-box .btn:contains("Apply")').click({ force: true });
		cy.visit('/desk#Form/Contact/Test Form Contact 3');
		cy.get('.prev-doc').should('be.visible').click();
		cy.get('.msgprint-dialog .modal-body').contains('No further records').should('be.visible');
		cy.get('.btn-modal-close:visible').click();
		cy.get('.next-doc').click();
		cy.wait(200);
		cy.contains('Test Form Contact 2').should('not.exist');
		cy.get('.page-title .title-text').should('contain', 'Test Form Contact 1');
		// clear filters
		cy.window().its('frappe').then((frappe) => {
			let list_view = frappe.get_list_view('Contact');
			list_view.filter_area.filter_list.clear_filters();
		});
	});
});
<|endoftext|>


<commit_before>/**
 * Created with RubyMine.
 * User: teamco
 * Date: 3/7/14
 * Time: 7:39 PM
 */

define([
    'plugins/preferences/preferences'
], function defineWidgetPreferences(BasePreferences) {

    /**
     * Define prefs
     * @class WidgetPreferences
     * @extends Renderer
     * @extends BasePreferences
     * @constructor
     */
    var WidgetPreferences = function WidgetPreferences() {

    };

    return WidgetPreferences.extend('WidgetPreferences', {

        /**
         * Define default widget prefs
         * @type {{
         *      title: {type: string, disabled: boolean, value},
         *      widgetUrl: {type: string, disabled: boolean, value},
         *      description: {type: string, disabled: boolean, value}
         * }}
         */
        defaultPrefs: {
            title: {
                type: 'text',
                disabled: false,
                value: undefined
            },
            description: {
                type: 'textarea',
                disabled: false,
                value: undefined
            },
            widgetUrl: {
                type: 'text',
                disabled: true,
                value: undefined
            }
        },

        /**
         * Render data
         * @memberOf WidgetPreferences
         * @param data
         */
        renderData: function renderData(data) {

            /**
             * Define dom nodes
             * @type {Array}
             */
            var nodes = [];

            /**
             * Merge prefs with default data
             */
            data = $.extend(true, this.defaultPrefs, data);

            for (var index in data) {

                if (data.hasOwnProperty(index)) {

                    /**
                     * Define text
                     * @type {string}
                     */
                    var text = index.toPoint().humanize();

                    /**
                     * Define node
                     */
                    var node = data[index];

                    /**
                     * Define placeholder text
                     * @type {string}
                     */
                    var placeholder = 'Enter ' + text;

                    if (node.type === 'text') {

                        /**
                         * Get text field
                         * @type {*[]}
                         */
                        var textField = this.renderTextField({
                            name: index,
                            text: text,
                            placeholder: placeholder,
                            value: node.value,
                            disabled: node.disabled
                        });
                    }

                    if (node.type === 'textarea') {

                        /**
                         * Get text field
                         * @type {*[]}
                         */
                        var textField = this.renderTextArea({
                            name: index,
                            text: text,
                            placeholder: placeholder,
                            value: node.value,
                            disabled: node.disabled
                        });
                    }

                    nodes.push(
                        $('<li />').append(textField)
                    );
                }
            }

            this.$.append(
                this.renderInteractions(nodes)
            );
        },

        /**
         * Render Interactions
         * @member WidgetPreferences
         * @param {Array} nodes
         * @returns {*}
         */
        renderInteractions: function renderInteractions(nodes) {

            /**
             * Define controller
             * @type {*}
             */
            var controller = this.view.controller;

            /**
             * Define interactions container
             * @type {*|jQuery}
             */
            var $ul = $('<ul />').addClass('interactions');

            /**
             * Define dom prefs
             */
            var column = controller.getDOMPreferences('column'),
                row = controller.getDOMPreferences('row'),
                width = controller.getDOMPreferences('relWidth'),
                height = controller.getDOMPreferences('relHeight');

            nodes.push(
                $('<li />').append(
                    $('<fieldset />').append(
                        $('<legend />').text('Interactions').
                            on('click.toggle', this.toggleFieldset).attr({
                                title: 'Interactions'
                            }),

                        $ul.append([
                            this.renderPrefs('Column', column),
                            this.renderPrefs('Width', width),
                            this.renderPrefs('Row', row),
                            this.renderPrefs('Height', height)
                        ])
                    )
                )
            );

            return nodes;
        },

        /**
         * Render move
         * @memberOf WidgetPreferences
         * @param {string} side
         * @param value
         * @returns {*|jQuery}
         */
        renderPrefs: function renderPrefs(side, value) {

            /**
             * Define move
             * @type {*[]}
             */
            var $move = this.renderTextField({
                name: side.toLowerCase(),
                text: side,
                placeholder: side,
                value: value,
                disabled: true
            });

            return $('<li />').append($move);
        }

    }, BasePreferences.prototype);
});<commit_msg>fix widget prefs<commit_after>/**
 * Created with RubyMine.
 * User: teamco
 * Date: 3/7/14
 * Time: 7:39 PM
 */

define([
    'plugins/preferences/preferences'
], function defineWidgetPreferences(BasePreferences) {

    /**
     * Define prefs
     * @class WidgetPreferences
     * @extends Renderer
     * @extends BasePreferences
     * @constructor
     */
    var WidgetPreferences = function WidgetPreferences() {

    };

    return WidgetPreferences.extend('WidgetPreferences', {

        /**
         * Define default widget prefs
         * @type {{
         *      title: {type: string, disabled: boolean, value},
         *      widgetUrl: {type: string, disabled: boolean, value},
         *      description: {type: string, disabled: boolean, value}
         * }}
         */
        defaultPrefs: {
            title: {
                type: 'text',
                disabled: false,
                value: undefined
            },
            description: {
                type: 'textarea',
                disabled: false,
                value: undefined
            },
            widgetUrl: {
                type: 'text',
                disabled: true,
                value: undefined
            }
        },

        /**
         * Render data
         * @memberOf WidgetPreferences
         * @param data
         */
        renderData: function renderData(data) {

            /**
             * Define dom nodes
             * @type {Array}
             */
            var nodes = [], merge = {};

            /**
             * Merge prefs with default data
             */
            data = $.extend(true, merge, this.defaultPrefs, data);

            for (var index in data) {

                if (data.hasOwnProperty(index)) {

                    /**
                     * Define text
                     * @type {string}
                     */
                    var text = index.toPoint().humanize();

                    /**
                     * Define node
                     */
                    var node = data[index];

                    /**
                     * Define placeholder text
                     * @type {string}
                     */
                    var placeholder = 'Enter ' + text;

                    if (node.type === 'text') {

                        /**
                         * Get text field
                         * @type {*[]}
                         */
                        var textField = this.renderTextField({
                            name: index,
                            text: text,
                            placeholder: placeholder,
                            value: node.value,
                            disabled: node.disabled
                        });
                    }

                    if (node.type === 'textarea') {

                        /**
                         * Get text field
                         * @type {*[]}
                         */
                        var textField = this.renderTextArea({
                            name: index,
                            text: text,
                            placeholder: placeholder,
                            value: node.value,
                            disabled: node.disabled
                        });
                    }

                    nodes.push(
                        $('<li />').append(textField)
                    );
                }
            }

            this.$.append(
                this.renderInteractions(nodes)
            );
        },

        /**
         * Render Interactions
         * @member WidgetPreferences
         * @param {Array} nodes
         * @returns {*}
         */
        renderInteractions: function renderInteractions(nodes) {

            /**
             * Define controller
             * @type {*}
             */
            var controller = this.view.controller;

            /**
             * Define interactions container
             * @type {*|jQuery}
             */
            var $ul = $('<ul />').addClass('interactions');

            /**
             * Define dom prefs
             */
            var column = controller.getDOMPreferences('column'),
                row = controller.getDOMPreferences('row'),
                width = controller.getDOMPreferences('relWidth'),
                height = controller.getDOMPreferences('relHeight');

            nodes.push(
                $('<li />').append(
                    $('<fieldset />').append(
                        $('<legend />').text('Interactions').
                            on('click.toggle', this.toggleFieldset).attr({
                                title: 'Interactions'
                            }),

                        $ul.append([
                            this.renderPrefs('Column', column),
                            this.renderPrefs('Width', width),
                            this.renderPrefs('Row', row),
                            this.renderPrefs('Height', height)
                        ])
                    )
                )
            );

            return nodes;
        },

        /**
         * Render move
         * @memberOf WidgetPreferences
         * @param {string} side
         * @param value
         * @returns {*|jQuery}
         */
        renderPrefs: function renderPrefs(side, value) {

            /**
             * Define move
             * @type {*[]}
             */
            var $move = this.renderTextField({
                name: side.toLowerCase(),
                text: side,
                placeholder: side,
                value: value,
                disabled: true
            });

            return $('<li />').append($move);
        }

    }, BasePreferences.prototype);
});<|endoftext|>


<commit_before>import {
    REMOVE_FILTER,
    ADD_FILTER
} from "../actions/types";

//state is not application state, just the state
//this reducer is responsible for, e.g. creating books
//if state is undefined, set to null

export default function(state = {}, action) {
    switch (action.type) {
        case ADD_FILTER:
            //let newState = _.union([...state], [action.payload]);
            //return newState;
            return [...state, action.payload];

        case REMOVE_FILTER:
            return action.payload;

        default:
            return state;
    }

}<commit_msg>filters reducer<commit_after>import {
    REMOVE_FILTER,
    ADD_FILTER
} from "../actions/types";

//state is not application state, just the state
//this reducer is responsible for, e.g. creating books
//if state is undefined, set to null

export default function(state = [] , action) {
    switch (action.type) {
        case ADD_FILTER:
            //let newState = _.union([...state], [action.payload]);
            //return newState;
            return [...state, action.payload];

        case REMOVE_FILTER:
            return action.payload;

        default:
            return state;
    }

}<|endoftext|>


<commit_before>var http = require('http');
var url = require('url');
var _ = require('underscore');
var httpio = require('./httpio.js');
var proxyUtils = require('./proxyUtils.js');

/*
 * CORE CONCEPTS
 *
 * Client - The source of the original request the proxy is responding to
 * Proxy - This service
 * Registry - The service containing mappings for end point service-name to end point hostname/port
 * Docker Rgsitry - DOcker Remote API Regsitry
 * End Point - The service the client wishes to contact
 *
 *
 */

var proxyPort = process.env.SP_PROXY_PORT || 8888;
var registryPort = process.env.SP_REGISTRY_PORT || 8888;
var registryHost = process.env.SP_REGISTRY_HOST || '172.17.0.6';
var dockerApiHost = process.env.SP_DOCKER_HOST || '172.17.42.1';
var dockerApiPort = process.env.SP_DOCKER_PORT || '4321';
var BAD_GATEWAY_RESPONSE_CODE = 502;

http.createServer(coreHandler).listen(proxyPort, httpStartupComplete);

function httpStartupComplete() {
    'use strict';
    console.log("To set Proxy Port/Docker REST Api/GNS Host:");
    console.log("export SP_PROXY_PORT=8081");
    console.log("export SP_DOCKER_HOST=172.14.0.2");
    console.log("export SP_DOCKER_PORT=4321");
    console.log("export SP_REGISTRY_HOST=192.168.0.6");
    console.log("export SP_REGISTRY_PORT=8888");
    console.log("starting sp proxy service http server on port " + proxyPort);
}

function coreHandler(clientRequest, clientResponse) {
    'use strict';
    clientRequest.clientIp = clientRequest.headers['x-forwarded-for'] || clientRequest.connection.remoteAddress;
    var servicename = clientRequest.headers.host;
    console.log('coreHandler() client request for servicename=' + servicename);
    var proxyCallbackHandler = proxyRequest(clientRequest, clientResponse);

     var requestUrl = url.parse(clientRequest.url, true, false);
    console.log("coreHandler() requestUrl=" + requestUrl.path);
    if (requestUrl.path.lastIndexOf('/spapi', 0) === 0 ) {
        dockerLookup(servicename,  proxyCallbackHandler);
    } else {
        registryLookup(servicename,  proxyCallbackHandler);
    }

}

function dockerLookup(servicename, proxyCallbackHandler) {
    console.log('dockerLookup() servicename=' + servicename);
    var dockerApiPort = '4321';
    var path = '/containers/' + servicename + '/json';
    var errCallback = function(err) {console.log("error contacting docker: " + err.message) };
    console.log("dockerApiHost=%s, dockerApiPort=%s",dockerApiHost, dockerApiPort);
    var dockerCallBack = function(body) {
        var dockerResponse = JSON.parse(body);
        //console.log("dockerCallBack() dockerResponse=" +body);
        if (! dockerResponse.NetworkSettings) {
                _sendBadGateway(serviceName, res);
                return;
            }
            var host = dockerResponse.NetworkSettings.IPAddress;
            var keys = dockerResponse.Config.ExposedPorts;
            var port = '';
            for (var key in keys) {
              port = key.split('/')[0];
            }
            console.log("got ip/port from docker: " + host + ':' + port);
            proxyCallbackHandler(host, port, true);
    }

    httpio.getJson(dockerApiHost, dockerApiPort, path, dockerCallBack, errCallback);
}

function registryLookup(servicename, proxyCallbackHandler) {
    console.log('registryLookup() servicename=' + servicename);
    var path = '/service/' + servicename + '/host/next';
    var errCallback = function(err) {console.log("error contacting registry: " + err.message) };
    var registryCallBack = function(body) {
        registryResponse = JSON.parse(body);
        //console.log("registryCallBack() registryResponse=" +registryResponse);
        proxyCallbackHandler(registryResponse.host, registryResponse.port);
    }
    httpio.getJson(registryHost, registryPort, path, registryCallBack, errCallback);
}

function proxyRequest(clientRequest, clientResponse) {
   'use strict';
   //console.log('proxyRequest() returning proxy function...');

    return function(host, port, clipPath) {
          //console.log('proxyRequest() for host=' + host);
          var requestUrl = url.parse(clientRequest.url, true, false);
          var path = '';
            if (clipPath) {
                path = proxyUtils.convertApiPath(requestUrl.path);
            }
           //var host = clientRequest.headers.host;

            var options = {
                method: clientRequest.method,
                hostname: host,
                host: host,
                port: port,
                path: path,
                headers: clientRequest.headers
            };

            _.extend(options.headers, {
                host: host,
                "x-forwarded-for": clientRequest.clientIp
            });

         console.log('proxyRequest() creating proxy request ' + options.method + ' http://' + host + ':' + options.port + options.path);

        var endPointResponseFunction = endPointResponseHandler(clientRequest, clientResponse, options, host, requestUrl)
        var endPointRequest = http.request(options, endPointResponseFunction);

           endPointRequest.on('error', function (error) {
                console.log("proxyRequest() endPointRequest.on('error') err=" + error.message );
                clientResponse.statusCode = BAD_GATEWAY_RESPONSE_CODE;
                clientResponse.end();
            });

            clientRequest.on('data', function (data) {
                console.log("proxyRequest() endPointRequest.on('data') data=" + data);
                endPointRequest.write(data);
            });

            clientRequest.on('end', function () {
                //console.log("proxyRequest() endPointRequest.on('end')");
                endPointRequest.end();

            });

    }

}

function endPointResponseHandler(clientRequest, clientResponse, options, host, requestUrl) {

   console.log("endPointResponseHandler() host=" + host);

    return function (endPointResponse) {
        clientResponse.statusCode = endPointResponse.statusCode;

        _.each(endPointResponse.headers, function (headerValue, headerKey) {
            clientResponse.setHeader(headerKey, headerValue);
        });

        endPointResponse.on('error', function (error) {
            console.log("endPointResponseHandler() endPointResponse.on('error')");
            clientResponse.connection.destroy();

        });

        endPointResponse.on('data', function (chunk) {
            //console.log("endPointResponseHandler() endPointResponse.on('data') clientResponse.write chunk=" + chunk);
            clientResponse.write(chunk);
        });

        endPointResponse.on('end', function () {
            //console.log("endPointResponseHandler() endPointResponse.on('end') calling clientResponse.end() ");
            clientResponse.end();

        });

        endPointResponse.on('close', function () {
            // console.log("endPointResponseHandler() endPointResponse.on('close')");
            clientResponse.connection.destroy();
        });
    }

}

function _sendBadGateway(response) {
    'use strict';
    response.statusCode = BAD_GATEWAY_RESPONSE_CODE;
    response.end();
}
<commit_msg>change proxy logging output for better debug and support<commit_after>var http = require('http');
var url = require('url');
var _ = require('underscore');
var httpio = require('./httpio.js');
var proxyUtils = require('./proxyUtils.js');

/*
 * CORE CONCEPTS
 *
 * Client - The source of the original request the proxy is responding to
 * Proxy - This service
 * Registry - The service containing mappings for end point service-name to end point hostname/port
 * Docker Rgsitry - DOcker Remote API Regsitry
 * End Point - The service the client wishes to contact
 *
 *
 */

var proxyPort = process.env.SP_PROXY_PORT || 8888;
var registryPort = process.env.SP_REGISTRY_PORT || 8888;
var registryHost = process.env.SP_REGISTRY_HOST || '172.17.0.6';
var dockerApiHost = process.env.SP_DOCKER_HOST || '172.17.42.1';
var dockerApiPort = process.env.SP_DOCKER_PORT || '4321';
var BAD_GATEWAY_RESPONSE_CODE = 502;

http.createServer(coreHandler).listen(proxyPort, httpStartupComplete);

function httpStartupComplete() {
    'use strict';
    console.log("To set Proxy Port/Docker REST Api/GNS Host:");
    console.log("export SP_PROXY_PORT=%s", proxyPort);
    console.log("export SP_DOCKER_HOST=%s", dockerApiHost);
    console.log("export SP_DOCKER_PORT=%s", dockerApiPort);
    console.log("export SP_REGISTRY_HOST=%s", registryHost);
    console.log("export SP_REGISTRY_PORT=%s", registryPort);
    console.log("starting sp proxy service http server on port " + proxyPort);
}

function coreHandler(clientRequest, clientResponse) {
    'use strict';
    clientRequest.clientIp = clientRequest.headers['x-forwarded-for'] || clientRequest.connection.remoteAddress;
    var servicename = clientRequest.headers.host;
    console.log('coreHandler() client request for servicename=' + servicename);
    var proxyCallbackHandler = proxyRequest(clientRequest, clientResponse);

     var requestUrl = url.parse(clientRequest.url, true, false);
    console.log("coreHandler() requestUrl=" + requestUrl.path);
    if (requestUrl.path.lastIndexOf('/spapi', 0) === 0 ) {
        dockerLookup(servicename,  proxyCallbackHandler);
    } else {
        registryLookup(servicename,  proxyCallbackHandler);
    }

}

function dockerLookup(servicename, proxyCallbackHandler) {
    console.log('dockerLookup() servicename=' + servicename);
    var dockerApiPort = '4321';
    var path = '/containers/' + servicename + '/json';
    var errCallback = function(err) {console.log("error contacting docker: " + err.message) };
    console.log("dockerApiHost=%s, dockerApiPort=%s",dockerApiHost, dockerApiPort);
    var dockerCallBack = function(body) {
        var dockerResponse = JSON.parse(body);
        //console.log("dockerCallBack() dockerResponse=" +body);
        if (! dockerResponse.NetworkSettings) {
                _sendBadGateway(serviceName, res);
                return;
            }
            var host = dockerResponse.NetworkSettings.IPAddress;
            var keys = dockerResponse.Config.ExposedPorts;
            var port = '';
            for (var key in keys) {
              port = key.split('/')[0];
            }
            console.log("got ip/port from docker: " + host + ':' + port);
            proxyCallbackHandler(host, port, true);
    }

    httpio.getJson(dockerApiHost, dockerApiPort, path, dockerCallBack, errCallback);
}

function registryLookup(servicename, proxyCallbackHandler) {
    console.log('registryLookup() servicename=' + servicename);
    var path = '/service/' + servicename + '/host/next';
    var errCallback = function(err) {console.log("error contacting registry: " + err.message) };
    var registryCallBack = function(body) {
        registryResponse = JSON.parse(body);
        //console.log("registryCallBack() registryResponse=" +registryResponse);
        proxyCallbackHandler(registryResponse.host, registryResponse.port);
    }
    httpio.getJson(registryHost, registryPort, path, registryCallBack, errCallback);
}

function proxyRequest(clientRequest, clientResponse) {
   'use strict';
   //console.log('proxyRequest() returning proxy function...');

    return function(host, port, clipPath) {
          //console.log('proxyRequest() for host=' + host);
          var requestUrl = url.parse(clientRequest.url, true, false);
          var path = '';
            if (clipPath) {
                path = proxyUtils.convertApiPath(requestUrl.path);
            }
           //var host = clientRequest.headers.host;

            var options = {
                method: clientRequest.method,
                hostname: host,
                host: host,
                port: port,
                path: path,
                headers: clientRequest.headers
            };

            _.extend(options.headers, {
                host: host,
                "x-forwarded-for": clientRequest.clientIp
            });

         console.log('proxyRequest() creating proxy request ' + options.method + ' http://' + host + ':' + options.port + options.path);

        var endPointResponseFunction = endPointResponseHandler(clientRequest, clientResponse, options, host, requestUrl)
        var endPointRequest = http.request(options, endPointResponseFunction);

           endPointRequest.on('error', function (error) {
                console.log("proxyRequest() endPointRequest.on('error') err=" + error.message );
                clientResponse.statusCode = BAD_GATEWAY_RESPONSE_CODE;
                clientResponse.end();
            });

            clientRequest.on('data', function (data) {
                console.log("proxyRequest() endPointRequest.on('data') data=" + data);
                endPointRequest.write(data);
            });

            clientRequest.on('end', function () {
                //console.log("proxyRequest() endPointRequest.on('end')");
                endPointRequest.end();

            });

    }

}

function endPointResponseHandler(clientRequest, clientResponse, options, host, requestUrl) {

   console.log("endPointResponseHandler() host=" + host);

    return function (endPointResponse) {
        clientResponse.statusCode = endPointResponse.statusCode;

        _.each(endPointResponse.headers, function (headerValue, headerKey) {
            clientResponse.setHeader(headerKey, headerValue);
        });

        endPointResponse.on('error', function (error) {
            console.log("endPointResponseHandler() endPointResponse.on('error')");
            clientResponse.connection.destroy();

        });

        endPointResponse.on('data', function (chunk) {
            //console.log("endPointResponseHandler() endPointResponse.on('data') clientResponse.write chunk=" + chunk);
            clientResponse.write(chunk);
        });

        endPointResponse.on('end', function () {
            //console.log("endPointResponseHandler() endPointResponse.on('end') calling clientResponse.end() ");
            clientResponse.end();

        });

        endPointResponse.on('close', function () {
            // console.log("endPointResponseHandler() endPointResponse.on('close')");
            clientResponse.connection.destroy();
        });
    }

}

function _sendBadGateway(response) {
    'use strict';
    response.statusCode = BAD_GATEWAY_RESPONSE_CODE;
    response.end();
}
<|endoftext|>