<commit_before>/* global translations */

/* Magic Mirror
 * Translator (l10n)
 *
 * By Christopher Fenner https://github.com/CFenner
 * MIT Licensed.
 */
var Translator = (function () {
	/**
	 * Load a JSON file via XHR.
	 *
	 * @param {string} file Path of the file we want to load.
	 * @param {Function} callback Function called when done.
	 */
	function loadJSON(file, callback) {
		var xhr = new XMLHttpRequest();
		xhr.overrideMimeType("application/json");
		xhr.open("GET", file, true);
		xhr.onreadystatechange = function () {
			if (xhr.readyState === 4 && xhr.status === 200) {
				// needs error handler try/catch at least
				let fileinfo = null;
				try {
					fileinfo = JSON.parse(xhr.responseText);
				} catch (exception) {
					// nothing here, but don't die
					Log.error(" loading json file =" + file + " failed");
				}
				callback(fileinfo);
			}
		};
		xhr.send(null);
	}

	return {
		coreTranslations: {},
		coreTranslationsFallback: {},
		translations: {},
		translationsFallback: {},

		/**
		 * Load a translation for a given key for a given module.
		 *
		 * @param {Module} module The module to load the translation for.
		 * @param {string} key The key of the text to translate.
		 * @param {object} variables The variables to use within the translation template (optional)
		 * @returns {string} the translated key
		 */
		translate: function (module, key, variables) {
			variables = variables || {}; //Empty object by default

			/**
			 * Combines template and variables like:
			 * template: "Please wait for {timeToWait} before continuing with {work}."
			 * variables: {timeToWait: "2 hours", work: "painting"}
			 * to: "Please wait for 2 hours before continuing with painting."
			 *
			 * @param {string} template Text with placeholder
			 * @param {object} variables Variables for the placeholder
			 * @returns {string} the template filled with the variables
			 */
			function createStringFromTemplate(template, variables) {
				if (Object.prototype.toString.call(template) !== "[object String]") {
					return template;
				}
				if (variables.fallback && !template.match(new RegExp("{.+}"))) {
					template = variables.fallback;
				}
				return template.replace(new RegExp("{([^}]+)}", "g"), function (_unused, varName) {
					return varName in variables ? variables[varName] : "{" + varName + "}";
				});
			}

			if (this.translations[module.name] && key in this.translations[module.name]) {
				// Log.log("Got translation for " + key + " from module translation: ");
				return createStringFromTemplate(this.translations[module.name][key], variables);
			}

			if (key in this.coreTranslations) {
				// Log.log("Got translation for " + key + " from core translation.");
				return createStringFromTemplate(this.coreTranslations[key], variables);
			}

			if (this.translationsFallback[module.name] && key in this.translationsFallback[module.name]) {
				// Log.log("Got translation for " + key + " from module translation fallback.");
				return createStringFromTemplate(this.translationsFallback[module.name][key], variables);
			}

			if (key in this.coreTranslationsFallback) {
				// Log.log("Got translation for " + key + " from core translation fallback.");
				return createStringFromTemplate(this.coreTranslationsFallback[key], variables);
			}

			return key;
		},

		/**
		 * Load a translation file (json) and remember the data.
		 *
		 * @param {Module} module The module to load the translation file for.
		 * @param {string} file Path of the file we want to load.
		 * @param {boolean} isFallback Flag to indicate fallback translations.
		 * @param {Function} callback Function called when done.
		 */
		load(module, file, isFallback, callback) {
			Log.log(`${module.name} - Load translation${isFallback && " fallback"}: ${file}`);

			if (this.translationsFallback[module.name]) {
				callback();
				return;
			}

			loadJSON(module.file(file), (json) => {
				const property = isFallback ? "translationsFallback" : "translations";
				this[property][module.name] = json;
				callback();
			});
		},

		/**
		 * Load the core translations.
		 *
		 * @param {string} lang The language identifier of the core language.
		 */
		loadCoreTranslations: function (lang) {
			var self = this;

			if (lang in translations) {
				Log.log("Loading core translation file: " + translations[lang]);
				loadJSON(translations[lang], function (translations) {
					self.coreTranslations = translations;
				});
			} else {
				Log.log("Configured language not found in core translations.");
			}

			self.loadCoreTranslationsFallback();
		},

		/**
		 * Load the core translations fallback.
		 * The first language defined in translations.js will be used.
		 */
		loadCoreTranslationsFallback: function () {
			var self = this;

			// The variable `first` will contain the first
			// defined translation after the following line.
			for (var first in translations) {
				break;
			}

			if (first) {
				Log.log("Loading core translation fallback file: " + translations[first]);
				loadJSON(translations[first], function (translations) {
					self.coreTranslationsFallback = translations;
				});
			}
		}
	};
})();
<commit_msg>Use some es6 notation<commit_after>/* global translations */

/* Magic Mirror
 * Translator (l10n)
 *
 * By Christopher Fenner https://github.com/CFenner
 * MIT Licensed.
 */
var Translator = (function () {
	/**
	 * Load a JSON file via XHR.
	 *
	 * @param {string} file Path of the file we want to load.
	 * @param {Function} callback Function called when done.
	 */
	function loadJSON(file, callback) {
		const xhr = new XMLHttpRequest();
		xhr.overrideMimeType("application/json");
		xhr.open("GET", file, true);
		xhr.onreadystatechange = function () {
			if (xhr.readyState === 4 && xhr.status === 200) {
				// needs error handler try/catch at least
				let fileinfo = null;
				try {
					fileinfo = JSON.parse(xhr.responseText);
				} catch (exception) {
					// nothing here, but don't die
					Log.error(" loading json file =" + file + " failed");
				}
				callback(fileinfo);
			}
		};
		xhr.send(null);
	}

	return {
		coreTranslations: {},
		coreTranslationsFallback: {},
		translations: {},
		translationsFallback: {},

		/**
		 * Load a translation for a given key for a given module.
		 *
		 * @param {Module} module The module to load the translation for.
		 * @param {string} key The key of the text to translate.
		 * @param {object} variables The variables to use within the translation template (optional)
		 * @returns {string} the translated key
		 */
		translate: function (module, key, variables) {
			variables = variables || {}; //Empty object by default

			/**
			 * Combines template and variables like:
			 * template: "Please wait for {timeToWait} before continuing with {work}."
			 * variables: {timeToWait: "2 hours", work: "painting"}
			 * to: "Please wait for 2 hours before continuing with painting."
			 *
			 * @param {string} template Text with placeholder
			 * @param {object} variables Variables for the placeholder
			 * @returns {string} the template filled with the variables
			 */
			function createStringFromTemplate(template, variables) {
				if (Object.prototype.toString.call(template) !== "[object String]") {
					return template;
				}
				if (variables.fallback && !template.match(new RegExp("{.+}"))) {
					template = variables.fallback;
				}
				return template.replace(new RegExp("{([^}]+)}", "g"), function (_unused, varName) {
					return varName in variables ? variables[varName] : "{" + varName + "}";
				});
			}

			if (this.translations[module.name] && key in this.translations[module.name]) {
				// Log.log("Got translation for " + key + " from module translation: ");
				return createStringFromTemplate(this.translations[module.name][key], variables);
			}

			if (key in this.coreTranslations) {
				// Log.log("Got translation for " + key + " from core translation.");
				return createStringFromTemplate(this.coreTranslations[key], variables);
			}

			if (this.translationsFallback[module.name] && key in this.translationsFallback[module.name]) {
				// Log.log("Got translation for " + key + " from module translation fallback.");
				return createStringFromTemplate(this.translationsFallback[module.name][key], variables);
			}

			if (key in this.coreTranslationsFallback) {
				// Log.log("Got translation for " + key + " from core translation fallback.");
				return createStringFromTemplate(this.coreTranslationsFallback[key], variables);
			}

			return key;
		},

		/**
		 * Load a translation file (json) and remember the data.
		 *
		 * @param {Module} module The module to load the translation file for.
		 * @param {string} file Path of the file we want to load.
		 * @param {boolean} isFallback Flag to indicate fallback translations.
		 * @param {Function} callback Function called when done.
		 */
		load(module, file, isFallback, callback) {
			Log.log(`${module.name} - Load translation${isFallback && " fallback"}: ${file}`);

			if (this.translationsFallback[module.name]) {
				callback();
				return;
			}

			loadJSON(module.file(file), (json) => {
				const property = isFallback ? "translationsFallback" : "translations";
				this[property][module.name] = json;
				callback();
			});
		},

		/**
		 * Load the core translations.
		 *
		 * @param {string} lang The language identifier of the core language.
		 */
		loadCoreTranslations: function (lang) {
			if (lang in translations) {
				Log.log("Loading core translation file: " + translations[lang]);
				loadJSON(translations[lang], (translations) => {
					this.coreTranslations = translations;
				});
			} else {
				Log.log("Configured language not found in core translations.");
			}

			this.loadCoreTranslationsFallback();
		},

		/**
		 * Load the core translations fallback.
		 * The first language defined in translations.js will be used.
		 */
		loadCoreTranslationsFallback: function () {
			// The variable `first` will contain the first
			// defined translation after the following line.
			for (var first in translations) {
				break;
			}

			if (first) {
				Log.log("Loading core translation fallback file: " + translations[first]);
				loadJSON(translations[first], (translations) => {
					this.coreTranslationsFallback = translations;
				});
			}
		}
	};
})();
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

const NativeModules = require('../BatchedBridge/NativeModules');
const Platform = require('../Utilities/Platform');
const UIManagerProperties = require('./UIManagerProperties');

const defineLazyObjectProperty = require('../Utilities/defineLazyObjectProperty');

import NativeUIManager from './NativeUIManager';

const viewManagerConfigs = {};

const triedLoadingConfig = new Set();

let NativeUIManagerConstants = {};
let isNativeUIManagerConstantsSet = false;
function getConstants(): Object {
  if (!isNativeUIManagerConstantsSet) {
    NativeUIManagerConstants = NativeUIManager.getConstants();
    isNativeUIManagerConstantsSet = true;
  }
  return NativeUIManagerConstants;
}

function getViewManagerConfig(viewManagerName: string): any {
  if (
    viewManagerConfigs[viewManagerName] === undefined &&
    NativeUIManager.getConstantsForViewManager
  ) {
    try {
      viewManagerConfigs[
        viewManagerName
      ] = NativeUIManager.getConstantsForViewManager(viewManagerName);
    } catch (e) {
      viewManagerConfigs[viewManagerName] = null;
    }
  }

  const config = viewManagerConfigs[viewManagerName];
  if (config) {
    return config;
  }

  // If we're in the Chrome Debugger, let's not even try calling the sync
  // method.
  if (!global.nativeCallSyncHook) {
    return config;
  }

  if (
    NativeUIManager.lazilyLoadView &&
    !triedLoadingConfig.has(viewManagerName)
  ) {
    const result = NativeUIManager.lazilyLoadView(viewManagerName);
    triedLoadingConfig.add(viewManagerName);
    if (result != null && result.viewConfig != null) {
      getConstants()[viewManagerName] = result.viewConfig;
      lazifyViewManagerConfig(viewManagerName);
    }
  }

  return viewManagerConfigs[viewManagerName];
}

/* $FlowFixMe(>=0.123.0 site=react_native_fb) This comment suppresses an error
 * found when Flow v0.123.0 was deployed. To see the error, delete this comment
 * and run Flow. */
const UIManagerJS = {
  ...NativeUIManager,
  createView(
    reactTag: ?number,
    viewName: string,
    rootTag: number,
    props: Object,
  ): void {
    if (Platform.OS === 'ios' && viewManagerConfigs[viewName] === undefined) {
      // This is necessary to force the initialization of native viewManager
      // classes in iOS when using static ViewConfigs
      getViewManagerConfig(viewName);
    }

    NativeUIManager.createView(reactTag, viewName, rootTag, props);
  },
  getConstants(): Object {
    return getConstants();
  },
  getViewManagerConfig(viewManagerName: string): any {
    return getViewManagerConfig(viewManagerName);
  },
  hasViewManagerConfig(viewManagerName: string): boolean {
    return getViewManagerConfig(viewManagerName) != null;
  },
};

// TODO (T45220498): Remove this.
// 3rd party libs may be calling `NativeModules.UIManager.getViewManagerConfig()`
// instead of `UIManager.getViewManagerConfig()` off UIManager.js.
// This is a workaround for now.
// $FlowFixMe
NativeUIManager.getViewManagerConfig = UIManagerJS.getViewManagerConfig;

function lazifyViewManagerConfig(viewName) {
  const viewConfig = getConstants()[viewName];
  viewManagerConfigs[viewName] = viewConfig;
  if (viewConfig.Manager) {
    defineLazyObjectProperty(viewConfig, 'Constants', {
      get: () => {
        const viewManager = NativeModules[viewConfig.Manager];
        const constants = {};
        viewManager &&
          Object.keys(viewManager).forEach(key => {
            const value = viewManager[key];
            if (typeof value !== 'function') {
              constants[key] = value;
            }
          });
        return constants;
      },
    });
    defineLazyObjectProperty(viewConfig, 'Commands', {
      get: () => {
        const viewManager = NativeModules[viewConfig.Manager];
        const commands = {};
        let index = 0;
        viewManager &&
          Object.keys(viewManager).forEach(key => {
            const value = viewManager[key];
            if (typeof value === 'function') {
              commands[key] = index++;
            }
          });
        return commands;
      },
    });
  }
}

/**
 * Copies the ViewManager constants and commands into UIManager. This is
 * only needed for iOS, which puts the constants in the ViewManager
 * namespace instead of UIManager, unlike Android.
 */
if (Platform.OS === 'ios') {
  Object.keys(getConstants()).forEach(viewName => {
    lazifyViewManagerConfig(viewName);
  });
} else if (getConstants().ViewManagerNames) {
  NativeUIManager.getConstants().ViewManagerNames.forEach(viewManagerName => {
    defineLazyObjectProperty(NativeUIManager, viewManagerName, {
      get: () => NativeUIManager.getConstantsForViewManager(viewManagerName),
    });
  });
}

if (!global.nativeCallSyncHook) {
  Object.keys(getConstants()).forEach(viewManagerName => {
    if (!UIManagerProperties.includes(viewManagerName)) {
      if (!viewManagerConfigs[viewManagerName]) {
        viewManagerConfigs[viewManagerName] = getConstants()[viewManagerName];
      }
      defineLazyObjectProperty(NativeUIManager, viewManagerName, {
        get: () => {
          console.warn(
            `Accessing view manager configs directly off UIManager via UIManager['${viewManagerName}'] ` +
              `is no longer supported. Use UIManager.getViewManagerConfig('${viewManagerName}') instead.`,
          );

          return UIManagerJS.getViewManagerConfig(viewManagerName);
        },
      });
    }
  });
}

module.exports = UIManagerJS;
<commit_msg>Make PaperUIManager.getViewManagerConfig log thrown exceptions<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

const NativeModules = require('../BatchedBridge/NativeModules');
const Platform = require('../Utilities/Platform');
const UIManagerProperties = require('./UIManagerProperties');

const defineLazyObjectProperty = require('../Utilities/defineLazyObjectProperty');

import NativeUIManager from './NativeUIManager';

const viewManagerConfigs = {};

const triedLoadingConfig = new Set();

let NativeUIManagerConstants = {};
let isNativeUIManagerConstantsSet = false;
function getConstants(): Object {
  if (!isNativeUIManagerConstantsSet) {
    NativeUIManagerConstants = NativeUIManager.getConstants();
    isNativeUIManagerConstantsSet = true;
  }
  return NativeUIManagerConstants;
}

function getViewManagerConfig(viewManagerName: string): any {
  if (
    viewManagerConfigs[viewManagerName] === undefined &&
    NativeUIManager.getConstantsForViewManager
  ) {
    try {
      viewManagerConfigs[
        viewManagerName
      ] = NativeUIManager.getConstantsForViewManager(viewManagerName);
    } catch (e) {
      console.error(
        "NativeUIManager.getConstantsForViewManager('" +
          viewManagerName +
          "') threw an exception.",
        e,
      );
      viewManagerConfigs[viewManagerName] = null;
    }
  }

  const config = viewManagerConfigs[viewManagerName];
  if (config) {
    return config;
  }

  // If we're in the Chrome Debugger, let's not even try calling the sync
  // method.
  if (!global.nativeCallSyncHook) {
    return config;
  }

  if (
    NativeUIManager.lazilyLoadView &&
    !triedLoadingConfig.has(viewManagerName)
  ) {
    const result = NativeUIManager.lazilyLoadView(viewManagerName);
    triedLoadingConfig.add(viewManagerName);
    if (result != null && result.viewConfig != null) {
      getConstants()[viewManagerName] = result.viewConfig;
      lazifyViewManagerConfig(viewManagerName);
    }
  }

  return viewManagerConfigs[viewManagerName];
}

/* $FlowFixMe(>=0.123.0 site=react_native_fb) This comment suppresses an error
 * found when Flow v0.123.0 was deployed. To see the error, delete this comment
 * and run Flow. */
const UIManagerJS = {
  ...NativeUIManager,
  createView(
    reactTag: ?number,
    viewName: string,
    rootTag: number,
    props: Object,
  ): void {
    if (Platform.OS === 'ios' && viewManagerConfigs[viewName] === undefined) {
      // This is necessary to force the initialization of native viewManager
      // classes in iOS when using static ViewConfigs
      getViewManagerConfig(viewName);
    }

    NativeUIManager.createView(reactTag, viewName, rootTag, props);
  },
  getConstants(): Object {
    return getConstants();
  },
  getViewManagerConfig(viewManagerName: string): any {
    return getViewManagerConfig(viewManagerName);
  },
  hasViewManagerConfig(viewManagerName: string): boolean {
    return getViewManagerConfig(viewManagerName) != null;
  },
};

// TODO (T45220498): Remove this.
// 3rd party libs may be calling `NativeModules.UIManager.getViewManagerConfig()`
// instead of `UIManager.getViewManagerConfig()` off UIManager.js.
// This is a workaround for now.
// $FlowFixMe
NativeUIManager.getViewManagerConfig = UIManagerJS.getViewManagerConfig;

function lazifyViewManagerConfig(viewName) {
  const viewConfig = getConstants()[viewName];
  viewManagerConfigs[viewName] = viewConfig;
  if (viewConfig.Manager) {
    defineLazyObjectProperty(viewConfig, 'Constants', {
      get: () => {
        const viewManager = NativeModules[viewConfig.Manager];
        const constants = {};
        viewManager &&
          Object.keys(viewManager).forEach(key => {
            const value = viewManager[key];
            if (typeof value !== 'function') {
              constants[key] = value;
            }
          });
        return constants;
      },
    });
    defineLazyObjectProperty(viewConfig, 'Commands', {
      get: () => {
        const viewManager = NativeModules[viewConfig.Manager];
        const commands = {};
        let index = 0;
        viewManager &&
          Object.keys(viewManager).forEach(key => {
            const value = viewManager[key];
            if (typeof value === 'function') {
              commands[key] = index++;
            }
          });
        return commands;
      },
    });
  }
}

/**
 * Copies the ViewManager constants and commands into UIManager. This is
 * only needed for iOS, which puts the constants in the ViewManager
 * namespace instead of UIManager, unlike Android.
 */
if (Platform.OS === 'ios') {
  Object.keys(getConstants()).forEach(viewName => {
    lazifyViewManagerConfig(viewName);
  });
} else if (getConstants().ViewManagerNames) {
  NativeUIManager.getConstants().ViewManagerNames.forEach(viewManagerName => {
    defineLazyObjectProperty(NativeUIManager, viewManagerName, {
      get: () => NativeUIManager.getConstantsForViewManager(viewManagerName),
    });
  });
}

if (!global.nativeCallSyncHook) {
  Object.keys(getConstants()).forEach(viewManagerName => {
    if (!UIManagerProperties.includes(viewManagerName)) {
      if (!viewManagerConfigs[viewManagerName]) {
        viewManagerConfigs[viewManagerName] = getConstants()[viewManagerName];
      }
      defineLazyObjectProperty(NativeUIManager, viewManagerName, {
        get: () => {
          console.warn(
            `Accessing view manager configs directly off UIManager via UIManager['${viewManagerName}'] ` +
              `is no longer supported. Use UIManager.getViewManagerConfig('${viewManagerName}') instead.`,
          );

          return UIManagerJS.getViewManagerConfig(viewManagerName);
        },
      });
    }
  });
}

module.exports = UIManagerJS;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Spin } from 'antd'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'

import './Dashboard.scss'

class Dashboard extends Component {
  constructor (props) {
    super(props)
    this.state = {}
  }

  componentWillMount = () => {
    this.props.fetchDash()
  }

  transferData = (data) => {
    let xData = []
    let yData = []
    data.map((item, index) => {
      xData.push(item.x)
      yData.push(item.y)
    })

    return {
      'x': xData,
      'y': yData
    }
  }

  getOption = (balanceGraph) => {
    let newDashData = this.transferData(balanceGraph)
    let option = {
      grid: {
        // show: true,
        top: '13.5%',
        left: '1%',
        right: '5%',
        bottom: '13.5%',
        containLabel: true
      },
      // tooltip: false,
      xAxis: {
        type: 'category',
        boundaryGap: true,
        axisTick: {
          alignWithLabel: true,
          lineStyle: {}
        },
        splitLine: {
          show: true
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            width: 2
          }
        },
        axisLabel: {
          interval: 0,
          textStyle: {
            fontSize: 12
          }
        },
        data: newDashData.x
      },
      yAxis: {
        interval: 200,
        min: 0,
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLine: {
          lineStyle: {
            width: 2
          }
        },
        axisLabel: {
          textStyle: {
            fontSize: 12
          }
        }
      },
      silent: false,
      series: [
        {
          type: 'line',
          data: newDashData.y,
          itemStyle: {
            normal: {
            }
          },
          symbolSize: 9,
          label: {
            normal: {
              show: true,
              formatter: '{c}',
              textStyle: {
                fontSize: 13
              }
            }
          },
          lineStyle: {
            normal: {
              width: 3
            }
          },
          smooth: true
        }
      ]
    }
    return option
  }

  render () {
    const {
      isLoading,
      stats
    } = this.props

    // console.log(stats)
    return (

Dashboard

          <Spin spinning={isLoading}>
            <ReactEchartsCore
              echarts={echarts}
              option={this.getOption(stats)}
              notMerge
              lazyUpdate
              style={{
                height: 450
              }} />
          </Spin>

    )
  }
}

export default Dashboard
<commit_msg>add prop type to dashboard<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Spin } from 'antd'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'

import './Dashboard.scss'

class Dashboard extends Component {
  static propTypes = {
    fetchDash: PropTypes.func.isRequired
  }

  constructor (props) {
    super(props)
    this.state = {}
  }

  componentWillMount = () => {
    this.props.fetchDash()
  }

  transferData = (data) => {
    let xData = []
    let yData = []
    data.map((item, index) => {
      xData.push(item.x)
      yData.push(item.y)
    })

    return {
      'x': xData,
      'y': yData
    }
  }

  getOption = (balanceGraph) => {
    let newDashData = this.transferData(balanceGraph)
    let option = {
      grid: {
        // show: true,
        top: '13.5%',
        left: '1%',
        right: '5%',
        bottom: '13.5%',
        containLabel: true
      },
      // tooltip: false,
      xAxis: {
        type: 'category',
        boundaryGap: true,
        axisTick: {
          alignWithLabel: true,
          lineStyle: {}
        },
        splitLine: {
          show: true
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            width: 2
          }
        },
        axisLabel: {
          interval: 0,
          textStyle: {
            fontSize: 12
          }
        },
        data: newDashData.x
      },
      yAxis: {
        interval: 200,
        min: 0,
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLine: {
          lineStyle: {
            width: 2
          }
        },
        axisLabel: {
          textStyle: {
            fontSize: 12
          }
        }
      },
      silent: false,
      series: [
        {
          type: 'line',
          data: newDashData.y,
          itemStyle: {
            normal: {
            }
          },
          symbolSize: 9,
          label: {
            normal: {
              show: true,
              formatter: '{c}',
              textStyle: {
                fontSize: 13
              }
            }
          },
          lineStyle: {
            normal: {
              width: 3
            }
          },
          smooth: true
        }
      ]
    }
    return option
  }

  render () {
    const {
      isLoading,
      stats
    } = this.props

    // console.log(stats)
    return (

Dashboard

          <Spin spinning={isLoading}>
            <ReactEchartsCore
              echarts={echarts}
              option={this.getOption(stats)}
              notMerge
              lazyUpdate
              style={{
                height: 450
              }} />
          </Spin>

    )
  }
}

export default Dashboard
<|endoftext|>


<commit_before>/**
 * @module datasource-executor
 */
'use strict';

var _ = require('lodash');
var Promise = require('when').Promise;
var cast = require('./cast');
var Status = require('flora-cluster').Status;
var Profiler = require('./profiler');

/**
 * Actually execute a resolved request and call the DataSources.
 *
 * @param {Api}     api
 * @param {flora.Request} request
 * @param {Object}  dst         - DataSourceTree
 * @param {Function}callback
 */
module.exports = function execute(api, request, dst, callback) {
    dst._profiler = dst._profiler || new Profiler();
    executeDst(api, request, dst)
        .then(function (results) {
            callback(null, results);
        }, callback);
};

/**
 * Execute all DataSources.
 *
 * Executes all subFilters, the main request and the subRequests, and may be
 * recursively called by the subRequests.
 *
 * @param {Api}    api
 * @param {flora.Request} request
 * @param {Object} dst DataSourceTree
 * @return {Promise}
 * @private
 */
function executeDst(api, request, dst) {
    var globalResults;

    return (new Promise(function (resolve) {
            resolve();
        }))

        // Execute subFilters
        .then(function executeSubFilters() {
            var subFilters = [];
            if (dst.subFilters) {
                subFilters = dst.subFilters.map(function (subFilter) {
                    subFilter._profiler = dst._profiler;
                    return executeDst(api, request, subFilter);
                });
            }

            return Promise.all(subFilters);
        })

        // Adjust the main request's filter to include the results from the subFilters
        .then(function handleSubFilterResults(subFilterResults) {
            if (!dst.request.filter) return true;

            // Build filter array for the main request
            var parentValues = {};
            subFilterResults.forEach(function (subFilterResult) {
                subFilterResult = subFilterResult[0];
                var parentKey = subFilterResult.parentKey.join('-');
                parentValues[parentKey] = parentValues[parentKey] || [];
                parentValues[parentKey].push(subFilterResult.data.map(function (ff) {
                    return subFilterResult.childKey.map(function (childKeyPart) {
                        return ff[childKeyPart];
                    });
                }));
            });

            // Prevent duplicates for all parentValues properties
            for (var parentKeyIdx in parentValues) {
                for (var i = 0; i < parentValues[parentKeyIdx].length; i++) {
                    parentValues[parentKeyIdx][i] = _.uniq(parentValues[parentKeyIdx][i], false, String);
                }
            }

            // Replace "valueFromSubFilter" properties for the main resource
            // by the values from the parentValues object
            var requestFilter = [];
            dst.request.filter.forEach(function (filter) {
                var filterNew = [];
                filter.forEach(function (filterPart) {
                    if (dst._isEmpty) return;

                    if (!filterPart.valueFromSubFilter) {
                        filterNew.push(filterPart);
                        return;
                    }

                    var attributeIdx = Array.isArray(filterPart.attribute)
                        ? filterPart.attribute.join('-')
                        : filterPart.attribute;

                    if (!parentValues[attributeIdx]) {
                        throw new Error('Missing subFilter for attribute "' + filterPart.attribute + '"');
                    }

                    parentValues[attributeIdx].forEach(function (pv) {
                        if (dst._isEmpty) return;
                        if (pv.length === 0) {
                            // One of the subFilters return an empty result,
                            // so the main results will also be empty, no need to execute
                            dst._isEmpty = true;
                            filterNew.push(filterPart);
                            return;
                        }

                        var filterPartNew = _.clone(filterPart);

                        if (!Array.isArray(filterPart.attribute)) {
                            // We silently assume that childKey/parentKey have length 1
                            filterPartNew.value = pv.map(function (parentValue) {
                                return parentValue[0];
                            });
                        } else {
                            filterPartNew.value = [];
                            for (var j = 0; j < filterPart.attribute.length; j++) {
                                filterPartNew.value[j] = pv[j];
                            }
                        }

                        filterNew.push(filterPartNew);
                    });
                });
                requestFilter.push(filterNew);
            });

            dst.request.filter = requestFilter;
        })

        // Cast filter values to their storedType
        .then(function castFilterValues() {
            if (dst._isEmpty) return;
            if (!dst.request.filter) return;
            if (!dst.attributeOptions) return;

            dst.request.filter.forEach(function (filter) {
                if (!filter) return;

                filter.forEach(function (filterPart) {
                    var storedType;

                    if (Array.isArray(filterPart.attribute)) {
                        for (var j = 0; j < filterPart.attribute.length; j++) {
                            storedType = (dst.attributeOptions[filterPart.attribute[j]]) ?
                                dst.attributeOptions[filterPart.attribute[j]].storedType : null;
                            if (!storedType) continue;
                            if (Array.isArray(filterPart.value[j])) {
                                filterPart.value[j] = filterPart.value[j].map(function (valuePart) {
                                    return cast(valuePart, {type: storedType});
                                });
                            } else {
                                filterPart.value[j] = cast(filterPart.value[j], {type: storedType});
                            }
                        }
                    } else {
                        storedType = (dst.attributeOptions[filterPart.attribute]) ?
                            dst.attributeOptions[filterPart.attribute].storedType : null;
                        if (!storedType) return;
                        if (Array.isArray(filterPart.value)) {
                            filterPart.value = filterPart.value.map(function (valuePart) {
                                return cast(valuePart, {type: storedType});
                            });
                        } else {
                            filterPart.value = cast(filterPart.value, {type: storedType});
                        }
                    }
                });
            });
        })

        // extension: "preExecute" (resource)
        .then(function invokePreExecute() {
            var resource = api.getResource(dst.resourceName);
            if (resource && resource.extensions && resource.extensions.preExecute) {
                api.log.trace('handle: "preExecute" extension (%s)', dst.resourceName);
                resource.extensions.preExecute({
                    request: request,
                    dataSourceTree: dst
                });
            }
        })

        // Execute the main request
        .then(function executeMainRequest() {
            var result = {
                data: [],
                totalCount: 0
            };
            ['attributePath', 'dataSourceName', 'childKey', 'parentKey',
                'multiValuedParentKey', 'uniqueChildKey'].forEach(function (key) {
                if (dst.hasOwnProperty(key)) result[key] = dst[key];
            });

            return new Promise(function (resolve, reject) {
                if (dst._isEmpty) return resolve(result);

                var ds = api.dataSources[dst.request.type];
                if (!ds) return reject(new Error('Unknown DataSource type "' + dst.request.type + '"'));

                // TODO: Move requestName generation into request-resolver:
                var requestName = 'unnamedRequest';

                if (!dst.attributePath || !dst.attributePath.length) requestName = 'root';
                else requestName = dst.attributePath.join('.') + ':' + dst.dataSourceName;

                dst.request._status = request._status ? request._status.addChild('dataSourceRequests') : new Status();
                dst.request._status.set('requestName', requestName);
                dst.request._status.set('type', dst.request.type);

                if (request._explain) dst.request._explain = {};

                dst.request._profiler = dst._profiler.child(requestName);

                ds.process(dst.request, function (err, rows) {
                    dst.request._profiler.end();
                    dst.request._status.close();
                    if (dst.request._explain) {
                        if (err) dst.request._explain.error = '' + err;
                        if (!dst.request._explain.duration) {
                            dst.request._explain.duration = dst.request._profiler.getDuration();
                        }
                    }
                    if (err) {
                        err.info = err.info || {};
                        err.info.dataSource = requestName;
                        return reject(err);
                    }

                    result.data = rows.data;
                    result.totalCount = rows.totalCount;
                    resolve(result);
                });
            });
        })

        // Transform the main results, do type casting
        .then(function transformMainResults(mainResults) {
            if (!dst.attributeOptions) return mainResults;
            if (typeof dst.attributeOptions !== 'object') return mainResults;

            for (var idx in mainResults.data) {
                if (typeof mainResults.data[idx] !== 'object') continue;
                for (var key in mainResults.data[idx]) {
                    if (!dst.attributeOptions[key] || !dst.attributeOptions[key].type) continue;
                    mainResults.data[idx][key] = cast(mainResults.data[idx][key], dst.attributeOptions[key]);
                }
            }

            return mainResults;
        })

        // extension: "postExecute" (resource)
        .then(function invokePostExecute(mainResults) {
            var resource = api.getResource(dst.resourceName);
            if (resource && resource.extensions && resource.extensions.postExecute) {
                api.log.trace('handle: "postExecute" extension (%s)', dst.resourceName);
                resource.extensions.postExecute({
                    request: request,
                    rawResults: mainResults
                });
            }

            return mainResults;
        })

        // Add the main results to our global results array
        .then(function handleMainResults(mainResults) {
            globalResults = [mainResults];
            return mainResults;
        })

        // Execute the subRequests
        .then(function executeSubRequests(mainResults) {
            if (!dst.subRequests) return [];
            if (!mainResults || mainResults.data.length === 0) return [];

            // Prepare the subRequests that may be dependent from the main results.
            // "valueFromParentKey" properties are replaced by the appropriate values.
            var subRequests = dst.subRequests.map(function (subRequest) {
                var parentValues = [];

                mainResults.data.forEach(function (mainResult) {
                    var isNull = true;
                    var value = subRequest.parentKey.map(function (m) {
                        if (mainResult[m] !== null) isNull = false;
                        return mainResult[m];
                    });
                    if (!isNull) parentValues.push(value);
                });

                // Flatten multiValued keys (not supported for combined keys!)
                if (subRequest.parentKey.length === 1 &&
                    dst.attributeOptions &&
                    dst.attributeOptions[subRequest.parentKey[0]] &&
                    dst.attributeOptions[subRequest.parentKey[0]].multiValued) {
                    var newParentValues = [];
                    parentValues.forEach(function (parentValue) {
                        if (!Array.isArray(parentValue[0])) return;
                        newParentValues = newParentValues.concat(parentValue[0].map(function (value) {
                            return [value];
                        }));
                    });
                    parentValues = newParentValues;
                }

                parentValues = _.uniq(parentValues, false, String);

                subRequest.request.filter.forEach(function (filters) {
                    filters.forEach(function (filter) {
                        if (!filter.valueFromParentKey) return;
                        if (!Array.isArray(filter.attribute)) {
                            filter.value = parentValues.map(function (value) {
                                return value[0];
                            });
                        } else {
                            filter.value = parentValues;
                        }
                    });
                });

                subRequest._profiler = dst._profiler;
                return executeDst(api, request, subRequest);
            });

            return Promise.all(subRequests);
        })

        // Add the subRequest results to the global results array
        .then(function handleSubResults(subResults) {
            delete(dst._isEmpty); // clean up

            subResults.forEach(function (subResult) {
                globalResults = globalResults.concat(subResult);
            });
            return globalResults;
        });
}
<commit_msg>explain: added countRows<commit_after>/**
 * @module datasource-executor
 */
'use strict';

var _ = require('lodash');
var Promise = require('when').Promise;
var cast = require('./cast');
var Status = require('flora-cluster').Status;
var Profiler = require('./profiler');

/**
 * Actually execute a resolved request and call the DataSources.
 *
 * @param {Api}     api
 * @param {flora.Request} request
 * @param {Object}  dst         - DataSourceTree
 * @param {Function}callback
 */
module.exports = function execute(api, request, dst, callback) {
    dst._profiler = dst._profiler || new Profiler();
    executeDst(api, request, dst)
        .then(function (results) {
            callback(null, results);
        }, callback);
};

/**
 * Execute all DataSources.
 *
 * Executes all subFilters, the main request and the subRequests, and may be
 * recursively called by the subRequests.
 *
 * @param {Api}    api
 * @param {flora.Request} request
 * @param {Object} dst DataSourceTree
 * @return {Promise}
 * @private
 */
function executeDst(api, request, dst) {
    var globalResults;

    return (new Promise(function (resolve) {
            resolve();
        }))

        // Execute subFilters
        .then(function executeSubFilters() {
            var subFilters = [];
            if (dst.subFilters) {
                subFilters = dst.subFilters.map(function (subFilter) {
                    subFilter._profiler = dst._profiler;
                    return executeDst(api, request, subFilter);
                });
            }

            return Promise.all(subFilters);
        })

        // Adjust the main request's filter to include the results from the subFilters
        .then(function handleSubFilterResults(subFilterResults) {
            if (!dst.request.filter) return true;

            // Build filter array for the main request
            var parentValues = {};
            subFilterResults.forEach(function (subFilterResult) {
                subFilterResult = subFilterResult[0];
                var parentKey = subFilterResult.parentKey.join('-');
                parentValues[parentKey] = parentValues[parentKey] || [];
                parentValues[parentKey].push(subFilterResult.data.map(function (ff) {
                    return subFilterResult.childKey.map(function (childKeyPart) {
                        return ff[childKeyPart];
                    });
                }));
            });

            // Prevent duplicates for all parentValues properties
            for (var parentKeyIdx in parentValues) {
                for (var i = 0; i < parentValues[parentKeyIdx].length; i++) {
                    parentValues[parentKeyIdx][i] = _.uniq(parentValues[parentKeyIdx][i], false, String);
                }
            }

            // Replace "valueFromSubFilter" properties for the main resource
            // by the values from the parentValues object
            var requestFilter = [];
            dst.request.filter.forEach(function (filter) {
                var filterNew = [];
                filter.forEach(function (filterPart) {
                    if (dst._isEmpty) return;

                    if (!filterPart.valueFromSubFilter) {
                        filterNew.push(filterPart);
                        return;
                    }

                    var attributeIdx = Array.isArray(filterPart.attribute)
                        ? filterPart.attribute.join('-')
                        : filterPart.attribute;

                    if (!parentValues[attributeIdx]) {
                        throw new Error('Missing subFilter for attribute "' + filterPart.attribute + '"');
                    }

                    parentValues[attributeIdx].forEach(function (pv) {
                        if (dst._isEmpty) return;
                        if (pv.length === 0) {
                            // One of the subFilters return an empty result,
                            // so the main results will also be empty, no need to execute
                            dst._isEmpty = true;
                            filterNew.push(filterPart);
                            return;
                        }

                        var filterPartNew = _.clone(filterPart);

                        if (!Array.isArray(filterPart.attribute)) {
                            // We silently assume that childKey/parentKey have length 1
                            filterPartNew.value = pv.map(function (parentValue) {
                                return parentValue[0];
                            });
                        } else {
                            filterPartNew.value = [];
                            for (var j = 0; j < filterPart.attribute.length; j++) {
                                filterPartNew.value[j] = pv[j];
                            }
                        }

                        filterNew.push(filterPartNew);
                    });
                });
                requestFilter.push(filterNew);
            });

            dst.request.filter = requestFilter;
        })

        // Cast filter values to their storedType
        .then(function castFilterValues() {
            if (dst._isEmpty) return;
            if (!dst.request.filter) return;
            if (!dst.attributeOptions) return;

            dst.request.filter.forEach(function (filter) {
                if (!filter) return;

                filter.forEach(function (filterPart) {
                    var storedType;

                    if (Array.isArray(filterPart.attribute)) {
                        for (var j = 0; j < filterPart.attribute.length; j++) {
                            storedType = (dst.attributeOptions[filterPart.attribute[j]]) ?
                                dst.attributeOptions[filterPart.attribute[j]].storedType : null;
                            if (!storedType) continue;
                            if (Array.isArray(filterPart.value[j])) {
                                filterPart.value[j] = filterPart.value[j].map(function (valuePart) {
                                    return cast(valuePart, {type: storedType});
                                });
                            } else {
                                filterPart.value[j] = cast(filterPart.value[j], {type: storedType});
                            }
                        }
                    } else {
                        storedType = (dst.attributeOptions[filterPart.attribute]) ?
                            dst.attributeOptions[filterPart.attribute].storedType : null;
                        if (!storedType) return;
                        if (Array.isArray(filterPart.value)) {
                            filterPart.value = filterPart.value.map(function (valuePart) {
                                return cast(valuePart, {type: storedType});
                            });
                        } else {
                            filterPart.value = cast(filterPart.value, {type: storedType});
                        }
                    }
                });
            });
        })

        // extension: "preExecute" (resource)
        .then(function invokePreExecute() {
            var resource = api.getResource(dst.resourceName);
            if (resource && resource.extensions && resource.extensions.preExecute) {
                api.log.trace('handle: "preExecute" extension (%s)', dst.resourceName);
                resource.extensions.preExecute({
                    request: request,
                    dataSourceTree: dst
                });
            }
        })

        // Execute the main request
        .then(function executeMainRequest() {
            var result = {
                data: [],
                totalCount: 0
            };
            ['attributePath', 'dataSourceName', 'childKey', 'parentKey',
                'multiValuedParentKey', 'uniqueChildKey'].forEach(function (key) {
                if (dst.hasOwnProperty(key)) result[key] = dst[key];
            });

            return new Promise(function (resolve, reject) {
                if (dst._isEmpty) return resolve(result);

                var ds = api.dataSources[dst.request.type];
                if (!ds) return reject(new Error('Unknown DataSource type "' + dst.request.type + '"'));

                // TODO: Move requestName generation into request-resolver:
                var requestName = 'unnamedRequest';

                if (!dst.attributePath || !dst.attributePath.length) requestName = 'root';
                else requestName = dst.attributePath.join('.') + ':' + dst.dataSourceName;

                dst.request._status = request._status ? request._status.addChild('dataSourceRequests') : new Status();
                dst.request._status.set('requestName', requestName);
                dst.request._status.set('type', dst.request.type);

                if (request._explain) dst.request._explain = {};

                dst.request._profiler = dst._profiler.child(requestName);

                ds.process(dst.request, function (err, rows) {
                    dst.request._profiler.end();
                    dst.request._status.close();
                    if (dst.request._explain) {
                        if (!err && Array.isArray(rows.data)) {
                            dst.request._explain.countRows = rows.data.length;
                        }
                        if (err) dst.request._explain.error = '' + err;
                        if (!dst.request._explain.duration) {
                            dst.request._explain.duration = dst.request._profiler.getDuration();
                        }
                    }
                    if (err) {
                        err.info = err.info || {};
                        err.info.dataSource = requestName;
                        return reject(err);
                    }

                    result.data = rows.data;
                    result.totalCount = rows.totalCount;
                    resolve(result);
                });
            });
        })

        // Transform the main results, do type casting
        .then(function transformMainResults(mainResults) {
            if (!dst.attributeOptions) return mainResults;
            if (typeof dst.attributeOptions !== 'object') return mainResults;

            for (var idx in mainResults.data) {
                if (typeof mainResults.data[idx] !== 'object') continue;
                for (var key in mainResults.data[idx]) {
                    if (!dst.attributeOptions[key] || !dst.attributeOptions[key].type) continue;
                    mainResults.data[idx][key] = cast(mainResults.data[idx][key], dst.attributeOptions[key]);
                }
            }

            return mainResults;
        })

        // extension: "postExecute" (resource)
        .then(function invokePostExecute(mainResults) {
            var resource = api.getResource(dst.resourceName);
            if (resource && resource.extensions && resource.extensions.postExecute) {
                api.log.trace('handle: "postExecute" extension (%s)', dst.resourceName);
                resource.extensions.postExecute({
                    request: request,
                    rawResults: mainResults
                });
            }

            return mainResults;
        })

        // Add the main results to our global results array
        .then(function handleMainResults(mainResults) {
            globalResults = [mainResults];
            return mainResults;
        })

        // Execute the subRequests
        .then(function executeSubRequests(mainResults) {
            if (!dst.subRequests) return [];
            if (!mainResults || mainResults.data.length === 0) return [];

            // Prepare the subRequests that may be dependent from the main results.
            // "valueFromParentKey" properties are replaced by the appropriate values.
            var subRequests = dst.subRequests.map(function (subRequest) {
                var parentValues = [];

                mainResults.data.forEach(function (mainResult) {
                    var isNull = true;
                    var value = subRequest.parentKey.map(function (m) {
                        if (mainResult[m] !== null) isNull = false;
                        return mainResult[m];
                    });
                    if (!isNull) parentValues.push(value);
                });

                // Flatten multiValued keys (not supported for combined keys!)
                if (subRequest.parentKey.length === 1 &&
                    dst.attributeOptions &&
                    dst.attributeOptions[subRequest.parentKey[0]] &&
                    dst.attributeOptions[subRequest.parentKey[0]].multiValued) {
                    var newParentValues = [];
                    parentValues.forEach(function (parentValue) {
                        if (!Array.isArray(parentValue[0])) return;
                        newParentValues = newParentValues.concat(parentValue[0].map(function (value) {
                            return [value];
                        }));
                    });
                    parentValues = newParentValues;
                }

                parentValues = _.uniq(parentValues, false, String);

                subRequest.request.filter.forEach(function (filters) {
                    filters.forEach(function (filter) {
                        if (!filter.valueFromParentKey) return;
                        if (!Array.isArray(filter.attribute)) {
                            filter.value = parentValues.map(function (value) {
                                return value[0];
                            });
                        } else {
                            filter.value = parentValues;
                        }
                    });
                });

                subRequest._profiler = dst._profiler;
                return executeDst(api, request, subRequest);
            });

            return Promise.all(subRequests);
        })

        // Add the subRequest results to the global results array
        .then(function handleSubResults(subResults) {
            delete(dst._isEmpty); // clean up

            subResults.forEach(function (subResult) {
                globalResults = globalResults.concat(subResult);
            });
            return globalResults;
        });
}
<|endoftext|>


<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*jslint undef: true*/

/*
* Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/

var fs = require("fs");
var util = require("util");
var path = require("path");
var log4js = require("log4js");
var Driver = require("../interface/driver");
var CapabilityManager = require("../util/capabilitymanager");

/**
 * Driver wrapping web driver
 */
function SeleniumDriver(config, args) {
    Driver.call(this, config, args);

    this.logger = log4js.getLogger("SeleniumDriver");
}

util.inherits(SeleniumDriver, Driver);

SeleniumDriver.maxAttempt = 60; // will amount to 30 secs
SeleniumDriver.attemptInterval = 500; // millisec
SeleniumDriver.wdAppPath = "../util/webdriver";

/**
 * Calculate capabilities for the test session
 *
 * @private

 * @return capablities required for the test session or false on error
 */
SeleniumDriver.prototype.getCapabilities = function () {

    var self = this,
        caps = {
            "platform" : "ANY",
            "javascriptEnabled" : true,
            "seleniumProtocol" : "WebDriver"
        },
        tmpCaps,
        browserInfo,
        versionKey,
        cm;

    if (self.config.proxyUrl) {

      console.log(self.config.proxyUrl +":"+ self.config.useProxyForAll);
        if(self.config.useProxyForAll) {
            if ( self.args.proxy || self.args.proxy === undefined  ) {
                self.logger.debug("Adding Proxy Setting to the Browser");
                caps.proxy = {"httpProxy" : self.config.proxyUrl, "proxyType" : "manual"};
            } else {
                self.logger.debug("Descriptor overridden commandline proxy param. Not setting proxy in browser");
            }
        } else {
            if ( self.args.proxy) {
                self.logger.debug("Adding Proxy Setting to the Browser");
                caps.proxy = {"httpProxy" : self.config.proxyUrl, "proxyType" : "manual"};
            }  else {
                self.logger.debug("Descriptor overridden commandline proxy param. Not setting proxy in browser");
            }

        }

    }

    caps.browserName = self.args["browser"] || self.config["browser"];
    if (!caps.browserName) {
        caps.error = "Browser is not specified";
        return caps;
    }

    // if the user has passed capabilities as json
    if (self.config.capabilities) {
        cm = new CapabilityManager(self.config.capabilities);
        tmpCaps = cm.getCapability(caps.browserName);
        if (tmpCaps === null) {
            caps.error = "No related capability for " + caps.browserName + " in " + self.config.capabilities;
            return caps;
        }
        caps = tmpCaps;
    } else {
        // this is the case where user just provides browser as "firefox-10.0"
        browserInfo = caps.browserName.split("-", 2);
        if (browserInfo.length > 1) {
            caps.browserName = browserInfo[0];
            caps.version = browserInfo[1];
        } else {
            versionKey = caps.browserName + "Version";
            if (self.config[versionKey]) {
                caps.version = self.config[versionKey];
            }
        }
    }

    return caps;
};

/**
 * Driver interface method
 * Start the driver before it can execute test. Perform task such as connecting to selenium.
 *
 * @param callback function to call when the driver is ready to be used, with errorMsg if failed
 */
SeleniumDriver.prototype.start = function (callback) {
    var self = this,
        capabilities,
        wdHubHost,
        WdAppClass = require(SeleniumDriver.wdAppPath),
        wdApp,
        errorMsg;

    capabilities = this.getCapabilities();
    if (capabilities.error) {
        self.errorCallback(self.logger, capabilities.error, callback);
        return;
    }
    self.logger.debug("Capabilities :");
    self.logger.debug(capabilities);

    if ("phantomjs" === capabilities.browserName && self.config["ghostDriverHost"]) {
        wdHubHost = self.config["ghostDriverHost"];
        self.sessionId = "";
    } else {
        wdHubHost = self.config["seleniumHost"];
    }
    if (!wdHubHost) {
        self.errorCallback(self.logger, "Could not determine selenium host", callback);
        return;
    }

    if (self.sessionId) {
        self.logger.info("Connecting to selenium: " + wdHubHost);
    } else {
        self.logger.info("Connecting to selenium: " + wdHubHost + ", browser: " + capabilities.browserName + ", version: " + capabilities.version);
    }

    wdApp = new WdAppClass();
    wdApp.promise.Application.getInstance().on("uncaughtException", function (e) {
        errorMsg =  "Uncaught exception: " + e.message;
        if (self.testCallback) {
            self.errorCallback(self.logger, errorMsg, self.testCallback);
        } else {
            self.logger.error(errorMsg);
        }
    });

    self.webdriver = new wdApp.Builder().
        usingServer(wdHubHost).
        usingSession(self.sessionId).
        withCapabilities(capabilities).build();
    self.webdriver.By = wdApp.By;

    callback(null);
};

/**
 * Driver interface method
 * Tidy up the driver
 *
 * @param callback
 */
SeleniumDriver.prototype.stop = function (callback) {
    if (!this.sessionId) { // we were not given a session id
       this.webdriver.quit();
    }

    if (callback) { callback(null); }
};

/**
 * creates javascript that will be injected in the browser to run the test
 *
 * @private
 *
 * @param testParams parameters for this test
 * @params callback function to call if there was an error
 *
 * @return injectable javascript or false on error
 */
SeleniumDriver.prototype.createDriverJs = function (testParams, callback) {
    var self = this,
        logger = this.logger,
        scriptType = "test",
        testJs,
        testJsUrl = "",
        actionJs,
        actionJsUrl = "",
        testParamsJs,
        appSeedUrl,
        seed,
        runner,
        seedJs,
        runnerJs,
        libs,
        arrLib,
        testLibsUrl = "[]",
        testLibsJs = "",
        testLibs = [],
        lib,
        autoTest = false,
        serverBase,
        driverJs,
        i;

    testJs = testParams.test;
    actionJs = testParams.action;
    if (!testJs && !actionJs) {
        self.errorCallback(logger, "The test or the action js must be specified", callback);
        return false;
    }
    if (actionJs) {
        scriptType = "action";
    }

    appSeedUrl = self.config["defaultAppSeed"];
    seed = self.config["testSeed"];
    runner = self.config["testRunner"];
    seedJs = fs.readFileSync(seed, "utf-8");
    runnerJs = fs.readFileSync(runner, "utf-8");
    libs = testParams.lib;
    if (libs) {
        arrLib = libs.split(",");
    } else {
        arrLib = [];
    }

    testParamsJs = JSON.stringify(testParams);

    // html tests run themselves
    if (testJs && (".html" === path.extname(testJs))) {
        autoTest = true;
    } else {
        // if arrow server is not running, we inject the entire script else inject the URL and
        // let the browser pull in from the arrow server (helps with debugging and injection size
        // is manageable).
        serverBase = self.getArrowServerBase();
        if (false === serverBase) {

            try {
                for (i = 0; i < arrLib.length; i += 1) {
                    lib = arrLib[i];
                    if (0 === lib.length) { continue; }
                    self.logger.info("Loading dependency: " + lib);
                    testLibsJs += fs.readFileSync(lib, "utf-8");
                }

                if (testJs) {
                    self.logger.info("Loading test: " + testJs);
                    testLibsJs += fs.readFileSync(testJs, "utf-8");
                } else {
                    self.logger.info("Loading action: " + actionJs);
                    testLibsJs += fs.readFileSync(actionJs, "utf-8");
                }
            } catch (e) {
                callback(e);
                return false;
            }
        } else {
            for (i = 0; i < arrLib.length; i += 1) {
                lib = arrLib[i];
                if (0 === lib.length) { continue; }
                self.logger.info("Loading dependency: " + lib);
                testLibs.push(self.getRemoteUrl(lib));
            }
            testLibsUrl = JSON.stringify(testLibs);

            if (testJs) {
                self.logger.info("Loading test: " + testJs);
                testJsUrl = self.getRemoteUrl(testJs);
            } else {
                self.logger.info("Loading action: " + actionJs);
                actionJsUrl = self.getRemoteUrl(actionJs);
            }
        }
    }

    driverJs =
        "ARROW = {};" +
        "ARROW.autoTest = " + autoTest + ";" +
        "ARROW.testParams = " + testParamsJs + ";" +
        "ARROW.appSeed = \"" + appSeedUrl + "\";" +
        "ARROW.testLibs = " + testLibsUrl + ";" +
        "ARROW.scriptType = \"" + scriptType + "\";" +
        "ARROW.testScript = \"" + testJsUrl + "\";" +
        "ARROW.actionScript = \"" + actionJsUrl + "\";" +
        "ARROW.onSeeded = function() { " + testLibsJs + runnerJs + " };" + seedJs;

    this.logger.trace("Driver js: " + driverJs);
    return driverJs;
};

/**
 * Driver interface method, called by controllers
 *
 * @param page
 * @params callback function to call once navigated
 */
SeleniumDriver.prototype.navigate = function (page, callback) {
    var self = this,
        logger = this.logger,
        webdriver = this.webdriver,
        url;

    self.logger.info("Loading page: " + page);

    // local paths need to be served via test server
    url = self.getRemoteUrl(page);
    if (false === url) {
        self.errorCallback(logger, "Cannot load a local file without arrow_server running: " + page, callback);
    } else {
        webdriver.get(url).then(function () {
            callback();
        });
    }
};

/**
 * Driver interface method, called by controllers
 *
 * @param testConfig values from the config section in the descriptor ycb
 * @param testParams parameters for this test
 * @params callback function to call at the end of the test with errorMsg
 */
SeleniumDriver.prototype.executeAction = function (testConfig, testParams, callback) {
    var self = this,
        logger = this.logger,
        webdriver = this.webdriver,
        actionJs,
        page,
        driverJs,
        retryCount = 0,
        url;

    actionJs = testParams.action;
    page = testParams.page;
    if (!testParams.lib && self.args.params && self.args.params.lib) { testParams.lib = self.args.params.lib; }
    self.testCallback = callback; // save it so that async wd exception can be reported back

    driverJs = this.createDriverJs(testParams, callback);
    if (false === driverJs) {
        return;
    }

    function finializeAction(actionData) {
        logger.debug("Finalizing action");
        webdriver.executeScript("ARROW.actionReported = true;").then(function () {
            webdriver.waitForNextPage().then(function () {
                callback(null, actionData);
            });
        });
    }

    function collectActionReport() {
        var reportJson;

        retryCount += 1;
        logger.debug("Waiting for the action to finish, attempt: " + retryCount);
        webdriver.executeScript("return ARROW.actionReport;").then(function (report) {
            if (report) {
                reportJson = JSON.parse(report);
                if (reportJson.error) {
                    self.logger.error("Action error: " + reportJson.error);
                    self.errorCallback(logger, "Failed to execute the action: " + actionJs, callback);
                } else {
                    finializeAction(report.data);
                }
            } else if (retryCount > SeleniumDriver.maxAttempt) {
                self.errorCallback(logger, "Failed to execute the action", callback);
            } else {
                setTimeout(collectActionReport, SeleniumDriver.attemptInterval);
            }
        });
    }

    function initAction() {
        webdriver.executeScript(driverJs).then(function () {
            setTimeout(collectActionReport, SeleniumDriver.attemptInterval);
        });
    }

    if (page) {
        self.logger.info("Loading page: " + page);

        // local paths need to be served via test server
        url = self.getRemoteUrl(page);
        if (false === url) {
            self.errorCallback(logger, "Cannot load a local file without arrow_server running: " + page, callback);
        } else {
            webdriver.get(url).then(function () {
                initAction();
            });
        }
    } else {
        initAction();
    }
};

/**
 * Driver interface method, called by controllers
 *
 * @param testConfig values from the config section in the descriptor ycb
 * @param testParams parameters for this test
 * @params callback function to call at the end of the test with errorMsg
 */
SeleniumDriver.prototype.executeTest = function (testConfig, testParams, callback) {
    var self = this,
        logger = this.logger,
        webdriver = this.webdriver,
        testJs,
        page,
        caps = [],
        driverJs,
        retryCount = 0,
        url;

    testJs = testParams.test;
    page = testParams.page;
    if (!testParams.lib && self.args.params && self.args.params.lib) { testParams.lib = self.args.params.lib; }
    self.testCallback = callback; // save it so that async wd exception can be reported back

    driverJs = this.createDriverJs(testParams, callback);
    if (false === driverJs) {
        return;
    }

    function collectTestReport() {
        retryCount += 1;
        logger.debug("Waiting for the test report, attempt: " + retryCount);
        webdriver.executeScript("return ARROW.testReport;").then(function (report) {

            if (report && JSON.stringify(report) !== "{}") {
                self.addReport(report, caps);
                showYUIConsoleLog();
                callback(null, report);

            } else if (retryCount > SeleniumDriver.maxAttempt) {
                showYUIConsoleLog();
                self.errorCallback(logger, "Failed to collect the test report", callback);
            } else {
                setTimeout(collectTestReport, SeleniumDriver.attemptInterval);
            }
        });
    }

    function showYUIConsoleLog() {

        webdriver.executeScript("return ARROW.consoleLog;").then(function (cLog) {
            if (cLog) {
                self.logger.debug("Debug Messages from Browser Console :" + "\n" + cLog);
            }
        });
    }

    function initTest() {

        webdriver.executeScript(driverJs).then(function () {
            setTimeout(collectTestReport, SeleniumDriver.attemptInterval);
        });
    }

    webdriver.session_.then(function (val) {
        logger.debug("Selenium session id: " + val.id);
        if (!val.id) {
            self.errorCallback(logger, "Unable to get a valid session, check your selenium config", callback);
            return;
        }

        caps = val.capabilities;
    });

    // in case of html test, we need to load the test as a page
    if (".html" === path.extname(testJs)) {
        page = path.resolve("", testJs);
    }

    if (page) {
        self.logger.info("Loading page: " + page);

        // local paths need to be served via test server
        url = self.getRemoteUrl(page);
        if (false === url) {
            self.errorCallback(logger, "Cannot load a local file without arrow_server running: " + page, callback);
        } else {
            webdriver.get(url).then(function () {
                initTest();
            });
        }
    } else {
        initTest();
    }
};

module.exports = SeleniumDriver;

<commit_msg>commenting console.log<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*jslint undef: true*/

/*
* Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/

var fs = require("fs");
var util = require("util");
var path = require("path");
var log4js = require("log4js");
var Driver = require("../interface/driver");
var CapabilityManager = require("../util/capabilitymanager");

/**
 * Driver wrapping web driver
 */
function SeleniumDriver(config, args) {
    Driver.call(this, config, args);

    this.logger = log4js.getLogger("SeleniumDriver");
}

util.inherits(SeleniumDriver, Driver);

SeleniumDriver.maxAttempt = 60; // will amount to 30 secs
SeleniumDriver.attemptInterval = 500; // millisec
SeleniumDriver.wdAppPath = "../util/webdriver";

/**
 * Calculate capabilities for the test session
 *
 * @private

 * @return capablities required for the test session or false on error
 */
SeleniumDriver.prototype.getCapabilities = function () {

    var self = this,
        caps = {
            "platform" : "ANY",
            "javascriptEnabled" : true,
            "seleniumProtocol" : "WebDriver"
        },
        tmpCaps,
        browserInfo,
        versionKey,
        cm;

    if (self.config.proxyUrl) {

      //console.log(self.config.proxyUrl +":"+ self.config.useProxyForAll);
        if(self.config.useProxyForAll) {
            if ( self.args.proxy || self.args.proxy === undefined  ) {
                self.logger.debug("Adding Proxy Setting to the Browser");
                caps.proxy = {"httpProxy" : self.config.proxyUrl, "proxyType" : "manual"};
            } else {
                self.logger.debug("Descriptor overridden commandline proxy param. Not setting proxy in browser");
            }
        } else {
            if ( self.args.proxy) {
                self.logger.debug("Adding Proxy Setting to the Browser");
                caps.proxy = {"httpProxy" : self.config.proxyUrl, "proxyType" : "manual"};
            }  else {
                self.logger.debug("Descriptor overridden commandline proxy param. Not setting proxy in browser");
            }

        }

    }

    caps.browserName = self.args["browser"] || self.config["browser"];
    if (!caps.browserName) {
        caps.error = "Browser is not specified";
        return caps;
    }

    // if the user has passed capabilities as json
    if (self.config.capabilities) {
        cm = new CapabilityManager(self.config.capabilities);
        tmpCaps = cm.getCapability(caps.browserName);
        if (tmpCaps === null) {
            caps.error = "No related capability for " + caps.browserName + " in " + self.config.capabilities;
            return caps;
        }
        caps = tmpCaps;
    } else {
        // this is the case where user just provides browser as "firefox-10.0"
        browserInfo = caps.browserName.split("-", 2);
        if (browserInfo.length > 1) {
            caps.browserName = browserInfo[0];
            caps.version = browserInfo[1];
        } else {
            versionKey = caps.browserName + "Version";
            if (self.config[versionKey]) {
                caps.version = self.config[versionKey];
            }
        }
    }

    return caps;
};

/**
 * Driver interface method
 * Start the driver before it can execute test. Perform task such as connecting to selenium.
 *
 * @param callback function to call when the driver is ready to be used, with errorMsg if failed
 */
SeleniumDriver.prototype.start = function (callback) {
    var self = this,
        capabilities,
        wdHubHost,
        WdAppClass = require(SeleniumDriver.wdAppPath),
        wdApp,
        errorMsg;

    capabilities = this.getCapabilities();
    if (capabilities.error) {
        self.errorCallback(self.logger, capabilities.error, callback);
        return;
    }
    self.logger.debug("Capabilities :");
    self.logger.debug(capabilities);

    if ("phantomjs" === capabilities.browserName && self.config["ghostDriverHost"]) {
        wdHubHost = self.config["ghostDriverHost"];
        self.sessionId = "";
    } else {
        wdHubHost = self.config["seleniumHost"];
    }
    if (!wdHubHost) {
        self.errorCallback(self.logger, "Could not determine selenium host", callback);
        return;
    }

    if (self.sessionId) {
        self.logger.info("Connecting to selenium: " + wdHubHost);
    } else {
        self.logger.info("Connecting to selenium: " + wdHubHost + ", browser: " + capabilities.browserName + ", version: " + capabilities.version);
    }

    wdApp = new WdAppClass();
    wdApp.promise.Application.getInstance().on("uncaughtException", function (e) {
        errorMsg =  "Uncaught exception: " + e.message;
        if (self.testCallback) {
            self.errorCallback(self.logger, errorMsg, self.testCallback);
        } else {
            self.logger.error(errorMsg);
        }
    });

    self.webdriver = new wdApp.Builder().
        usingServer(wdHubHost).
        usingSession(self.sessionId).
        withCapabilities(capabilities).build();
    self.webdriver.By = wdApp.By;

    callback(null);
};

/**
 * Driver interface method
 * Tidy up the driver
 *
 * @param callback
 */
SeleniumDriver.prototype.stop = function (callback) {
    if (!this.sessionId) { // we were not given a session id
       this.webdriver.quit();
    }

    if (callback) { callback(null); }
};

/**
 * creates javascript that will be injected in the browser to run the test
 *
 * @private
 *
 * @param testParams parameters for this test
 * @params callback function to call if there was an error
 *
 * @return injectable javascript or false on error
 */
SeleniumDriver.prototype.createDriverJs = function (testParams, callback) {
    var self = this,
        logger = this.logger,
        scriptType = "test",
        testJs,
        testJsUrl = "",
        actionJs,
        actionJsUrl = "",
        testParamsJs,
        appSeedUrl,
        seed,
        runner,
        seedJs,
        runnerJs,
        libs,
        arrLib,
        testLibsUrl = "[]",
        testLibsJs = "",
        testLibs = [],
        lib,
        autoTest = false,
        serverBase,
        driverJs,
        i;

    testJs = testParams.test;
    actionJs = testParams.action;
    if (!testJs && !actionJs) {
        self.errorCallback(logger, "The test or the action js must be specified", callback);
        return false;
    }
    if (actionJs) {
        scriptType = "action";
    }

    appSeedUrl = self.config["defaultAppSeed"];
    seed = self.config["testSeed"];
    runner = self.config["testRunner"];
    seedJs = fs.readFileSync(seed, "utf-8");
    runnerJs = fs.readFileSync(runner, "utf-8");
    libs = testParams.lib;
    if (libs) {
        arrLib = libs.split(",");
    } else {
        arrLib = [];
    }

    testParamsJs = JSON.stringify(testParams);

    // html tests run themselves
    if (testJs && (".html" === path.extname(testJs))) {
        autoTest = true;
    } else {
        // if arrow server is not running, we inject the entire script else inject the URL and
        // let the browser pull in from the arrow server (helps with debugging and injection size
        // is manageable).
        serverBase = self.getArrowServerBase();
        if (false === serverBase) {

            try {
                for (i = 0; i < arrLib.length; i += 1) {
                    lib = arrLib[i];
                    if (0 === lib.length) { continue; }
                    self.logger.info("Loading dependency: " + lib);
                    testLibsJs += fs.readFileSync(lib, "utf-8");
                }

                if (testJs) {
                    self.logger.info("Loading test: " + testJs);
                    testLibsJs += fs.readFileSync(testJs, "utf-8");
                } else {
                    self.logger.info("Loading action: " + actionJs);
                    testLibsJs += fs.readFileSync(actionJs, "utf-8");
                }
            } catch (e) {
                callback(e);
                return false;
            }
        } else {
            for (i = 0; i < arrLib.length; i += 1) {
                lib = arrLib[i];
                if (0 === lib.length) { continue; }
                self.logger.info("Loading dependency: " + lib);
                testLibs.push(self.getRemoteUrl(lib));
            }
            testLibsUrl = JSON.stringify(testLibs);

            if (testJs) {
                self.logger.info("Loading test: " + testJs);
                testJsUrl = self.getRemoteUrl(testJs);
            } else {
                self.logger.info("Loading action: " + actionJs);
                actionJsUrl = self.getRemoteUrl(actionJs);
            }
        }
    }

    driverJs =
        "ARROW = {};" +
        "ARROW.autoTest = " + autoTest + ";" +
        "ARROW.testParams = " + testParamsJs + ";" +
        "ARROW.appSeed = \"" + appSeedUrl + "\";" +
        "ARROW.testLibs = " + testLibsUrl + ";" +
        "ARROW.scriptType = \"" + scriptType + "\";" +
        "ARROW.testScript = \"" + testJsUrl + "\";" +
        "ARROW.actionScript = \"" + actionJsUrl + "\";" +
        "ARROW.onSeeded = function() { " + testLibsJs + runnerJs + " };" + seedJs;

    this.logger.trace("Driver js: " + driverJs);
    return driverJs;
};

/**
 * Driver interface method, called by controllers
 *
 * @param page
 * @params callback function to call once navigated
 */
SeleniumDriver.prototype.navigate = function (page, callback) {
    var self = this,
        logger = this.logger,
        webdriver = this.webdriver,
        url;

    self.logger.info("Loading page: " + page);

    // local paths need to be served via test server
    url = self.getRemoteUrl(page);
    if (false === url) {
        self.errorCallback(logger, "Cannot load a local file without arrow_server running: " + page, callback);
    } else {
        webdriver.get(url).then(function () {
            callback();
        });
    }
};

/**
 * Driver interface method, called by controllers
 *
 * @param testConfig values from the config section in the descriptor ycb
 * @param testParams parameters for this test
 * @params callback function to call at the end of the test with errorMsg
 */
SeleniumDriver.prototype.executeAction = function (testConfig, testParams, callback) {
    var self = this,
        logger = this.logger,
        webdriver = this.webdriver,
        actionJs,
        page,
        driverJs,
        retryCount = 0,
        url;

    actionJs = testParams.action;
    page = testParams.page;
    if (!testParams.lib && self.args.params && self.args.params.lib) { testParams.lib = self.args.params.lib; }
    self.testCallback = callback; // save it so that async wd exception can be reported back

    driverJs = this.createDriverJs(testParams, callback);
    if (false === driverJs) {
        return;
    }

    function finializeAction(actionData) {
        logger.debug("Finalizing action");
        webdriver.executeScript("ARROW.actionReported = true;").then(function () {
            webdriver.waitForNextPage().then(function () {
                callback(null, actionData);
            });
        });
    }

    function collectActionReport() {
        var reportJson;

        retryCount += 1;
        logger.debug("Waiting for the action to finish, attempt: " + retryCount);
        webdriver.executeScript("return ARROW.actionReport;").then(function (report) {
            if (report) {
                reportJson = JSON.parse(report);
                if (reportJson.error) {
                    self.logger.error("Action error: " + reportJson.error);
                    self.errorCallback(logger, "Failed to execute the action: " + actionJs, callback);
                } else {
                    finializeAction(report.data);
                }
            } else if (retryCount > SeleniumDriver.maxAttempt) {
                self.errorCallback(logger, "Failed to execute the action", callback);
            } else {
                setTimeout(collectActionReport, SeleniumDriver.attemptInterval);
            }
        });
    }

    function initAction() {
        webdriver.executeScript(driverJs).then(function () {
            setTimeout(collectActionReport, SeleniumDriver.attemptInterval);
        });
    }

    if (page) {
        self.logger.info("Loading page: " + page);

        // local paths need to be served via test server
        url = self.getRemoteUrl(page);
        if (false === url) {
            self.errorCallback(logger, "Cannot load a local file without arrow_server running: " + page, callback);
        } else {
            webdriver.get(url).then(function () {
                initAction();
            });
        }
    } else {
        initAction();
    }
};

/**
 * Driver interface method, called by controllers
 *
 * @param testConfig values from the config section in the descriptor ycb
 * @param testParams parameters for this test
 * @params callback function to call at the end of the test with errorMsg
 */
SeleniumDriver.prototype.executeTest = function (testConfig, testParams, callback) {
    var self = this,
        logger = this.logger,
        webdriver = this.webdriver,
        testJs,
        page,
        caps = [],
        driverJs,
        retryCount = 0,
        url;

    testJs = testParams.test;
    page = testParams.page;
    if (!testParams.lib && self.args.params && self.args.params.lib) { testParams.lib = self.args.params.lib; }
    self.testCallback = callback; // save it so that async wd exception can be reported back

    driverJs = this.createDriverJs(testParams, callback);
    if (false === driverJs) {
        return;
    }

    function collectTestReport() {
        retryCount += 1;
        logger.debug("Waiting for the test report, attempt: " + retryCount);
        webdriver.executeScript("return ARROW.testReport;").then(function (report) {

            if (report && JSON.stringify(report) !== "{}") {
                self.addReport(report, caps);
                showYUIConsoleLog();
                callback(null, report);

            } else if (retryCount > SeleniumDriver.maxAttempt) {
                showYUIConsoleLog();
                self.errorCallback(logger, "Failed to collect the test report", callback);
            } else {
                setTimeout(collectTestReport, SeleniumDriver.attemptInterval);
            }
        });
    }

    function showYUIConsoleLog() {

        webdriver.executeScript("return ARROW.consoleLog;").then(function (cLog) {
            if (cLog) {
                self.logger.debug("Debug Messages from Browser Console :" + "\n" + cLog);
            }
        });
    }

    function initTest() {

        webdriver.executeScript(driverJs).then(function () {
            setTimeout(collectTestReport, SeleniumDriver.attemptInterval);
        });
    }

    webdriver.session_.then(function (val) {
        logger.debug("Selenium session id: " + val.id);
        if (!val.id) {
            self.errorCallback(logger, "Unable to get a valid session, check your selenium config", callback);
            return;
        }

        caps = val.capabilities;
    });

    // in case of html test, we need to load the test as a page
    if (".html" === path.extname(testJs)) {
        page = path.resolve("", testJs);
    }

    if (page) {
        self.logger.info("Loading page: " + page);

        // local paths need to be served via test server
        url = self.getRemoteUrl(page);
        if (false === url) {
            self.errorCallback(logger, "Cannot load a local file without arrow_server running: " + page, callback);
        } else {
            webdriver.get(url).then(function () {
                initTest();
            });
        }
    } else {
        initTest();
    }
};

module.exports = SeleniumDriver;

<|endoftext|>


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

import module from 'poddetail/poddetail_module';

describe('CreatorInfo directive', () => {
  /** @type {!angular.Scope} */
  let scope;
  /** @type {function(!angular.Scope):!angular.JQLite} */
  let compileFn;

  beforeEach(() => {
    angular.mock.module(module.name);

    angular.mock.inject(($rootScope, $compile) => {
      scope = $rootScope.$new();
      compileFn = $compile('<kd-creator-info creator="creator"></kd-creator-info>');
    });
  });

  it('Should just display the kind of unknown creator kinds', () => {
    // given
    scope.creator = {kind: 'Unknown'};

    // when
    let element = compileFn(scope);
    scope.$digest();

    // then
    let span = element.find('span');
    expect(span.text().trim()).toEqual('Unknown');
  });

  const kind2directive = new Map([
    ['Job', 'job'],
    ['DaemonSet', 'daemon-set'],
    ['ReplicationController', 'replication-controller'],
    ['ReplicaSet', 'replica-set'],
    ['PetSet', 'pet-set'],
  ]);

  for (let [kind, directive] of kind2directive) {
    it(`should render a ${kind} as a kd-${directive}-card-list`, () => {
      // given
      scope.creator = {kind: kind};

      // when
      let element = compileFn(scope);
      scope.$digest();

      // then
      let elem = element.find(`kd-${directive}-card-list`);
      expect(elem.length).toEqual(1);
    });
  }
});
<commit_msg>Fix the test code to IE11 compatible code (#1388)<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import module from 'poddetail/poddetail_module';

describe('CreatorInfo directive', () => {
  /** @type {!angular.Scope} */
  let scope;
  /** @type {function(!angular.Scope):!angular.JQLite} */
  let compileFn;

  beforeEach(() => {
    angular.mock.module(module.name);

    angular.mock.inject(($rootScope, $compile) => {
      scope = $rootScope.$new();
      compileFn = $compile('<kd-creator-info creator="creator"></kd-creator-info>');
    });
  });

  it('Should just display the kind of unknown creator kinds', () => {
    // given
    scope.creator = {kind: 'Unknown'};

    // when
    let element = compileFn(scope);
    scope.$digest();

    // then
    let span = element.find('span');
    expect(span.text().trim()).toEqual('Unknown');
  });

  const kind2directive = new Map([
    ['Job', 'job'],
    ['DaemonSet', 'daemon-set'],
    ['ReplicationController', 'replication-controller'],
    ['ReplicaSet', 'replica-set'],
    ['PetSet', 'pet-set'],
  ]);

  kind2directive.forEach((directive, kind) => {
    it(`should render a ${kind} as a kd-${directive}-card-list`, () => {
      // given
      scope.creator = {kind: kind};

      // when
      let element = compileFn(scope);
      scope.$digest();

      // then
      let elem = element.find(`kd-${directive}-card-list`);
      expect(elem.length).toEqual(1);
    });
  });
});
<|endoftext|>