<commit_before>'use strict';
const _ = require('lodash');
const Base = require('yeoman-generator').Base;
const known = require('../../utils/known');

function extractFromReadme(content) {
  const safe = (p) => p ? p[1] : '';
  // between header and installation
  const longDescription = safe(content.match(/=====$\s([\s\S]*)^Installation/m)).trim();
  // usage till end line
  const readme = safe(content.match(/(^Usage[\s\S]*)^\*\*\*$/m)).trim();

  return {longDescription, readme};
}

function toPhoveaName(name) {
  return name.replace(/^caleydo_/, 'phovea_');
}

function toExtension(name, desc) {
  const copy = _.merge({}, desc);
  delete copy.type;
  delete copy.id;
  delete copy.file;
  return {
    type: desc.type,
    id: desc.id || name,
    module: desc.file || '',
    extras: copy
  };
}

class Generator extends Base {

  constructor(args, options) {
    super(args, options);

    this.argument('type', {
      required: false
    });
  }

  initializing() {
    if (this.args.length === 0) {
      return this._promptForType().then(this._initializingImpl.bind(this));
    }
    this.type = this.args[0];
    return this._initializingImpl();
  }

  _promptForType() {
    return this.prompt({
      type: 'list',
      name: 'type',
      message: 'Plugin Type',
      choices: known.plugin.types,
      default: 'lib'
    }).then((props) => {
      this.type = props.type;
    });
  }

  _initializingImpl() {
    const pkg = this.fs.readJSON(this.destinationPath('package.json'));

    const {longDescription, readme} = extractFromReadme(this.fs.read(this.destinationPath('README.md')));

    this.props = {
      useDefaults: true,
      noSamples: true,
      description: (pkg.description || '').replace(/Caleydo Web/g, 'Phovea'),
      longDescription: longDescription.replace(/Caleydo Web/g, 'Phovea'),
      readme: readme.replace(/Caleydo Web/g, 'Phovea').replace(/\.\.\/caleydo_/g, 'phovea_'),
      authorEmail: 'contact@caleydo.org',
      authorUrl: 'https://caleydo.org'
    };
    const name = toPhoveaName(pkg.name);

    const safe = (obj, p, default_) => {
      var act = obj;
      for (let pi of p.split('.')) {
        if (!act) {
          return default_;
        }
        act = act[pi];
      }
      return act ? act : default_;
    };

    const validLib = (p) => {
      const r = known.lib.exists(p);
      if (!r) {
        this.log('ERROR: cant find lib: ', p);
        return false;
      }
      return true;
    };
    const validPlugin = (p) => {
      const r = known.plugin.exists(p);
      if (!r) {
        this.log('ERROR: cant find plugin: ', p);
        return false;
      }
      return true;
    };

    const libs = safe(pkg.caleydo, 'dependencies.web', {});

    const requirement2lib = {};
    known.lib.listServer.forEach((p) => {
      Object.keys(p.requirements).forEach((r) => {
        requirement2lib[r] = p;
      });
    });
    const knownRequirements = [].concat(...known.lib.listServer.map((m) => Object.keys(m.requirements)));
    const knownDebianPackages = [].concat(...known.lib.listServer.map((m) => Object.keys(m.debianPackages)));
    const knownRedhatPackages = [].concat(...known.lib.listServer.map((m) => Object.keys(m.redhatPackages)));

    const slibs = safe(pkg.caleydo, 'dependencies.python', {});
    const debianPackages = safe(pkg.caleydo, 'dependencies.debian', {});
    const redhatPackages = safe(pkg.caleydo, 'dependencies.redhat', {});

    this.config.defaults({
      type: this.type,
      name: name,
      author: 'The Caleydo Team',
      githubAccount: 'phovea',
      modules: Object.keys(pkg.peerDependencies).map(toPhoveaName).filter(validPlugin),
      extensions: safe(pkg.caleydo, 'plugins.web', []).map(toExtension.bind(this, name)),
      sextensions: safe(pkg.caleydo, 'plugins.python', []).map(toExtension.bind(this, name)),

      // merge valid web libraries with valid looked up server libraries
      libraries: Object.keys(libs)
        .filter(validLib).concat(
          Object.keys(slibs).filter((d) => knownRequirements.indexOf(d) >= 0).map((d) => requirement2lib[d])),

      unknown: {
        // filter unknown and convert to the common format
        requirements: Object.keys(slibs).filter((d) => knownRequirements.indexOf(d) < 0).map((d) => d + slibs[d]),
        debianPackages: Object.keys(debianPackages).filter((d) => knownDebianPackages.indexOf(d) < 0).map((d) => d + debianPackages[d]),
        redhatPackages: Object.keys(redhatPackages).filter((d) => knownRedhatPackages.indexOf(d) < 0).map((d) => d + redhatPackages[d])
      }
    });
  }

  default() {
    this.composeWith('phovea:init-' + this.type, {
      options: this.props
    }, {
      local: require.resolve('../init-' + this.type)
    });
  }

  writing() {
    this.fs.delete(this.destinationPath('__index__.py'));
    this.fs.delete(this.destinationPath('.gitignore'));
    this.fs.delete(this.destinationPath('.npmignore'));
    this.fs.delete(this.destinationPath('.gitattributes'));
    this.fs.delete(this.destinationPath('LICENSE'));
    this.fs.delete(this.destinationPath('package.json'));

    this.fs.move(this.destinationPath('**.ts'), this.destinationPath('src/'));
    if (this.fs.exists(this.destinationPath('src/main.ts'))) {
      this.fs.move(this.destinationPath('src/main.ts'), this.destinationPath('src/index.ts'));
    }
    this.fs.move(this.destinationPath('*.scss'), this.destinationPath('src/'));
    this.fs.move(this.destinationPath('*.py'), this.destinationPath(this.config.get('name') + '/'));
    if (this.fs.exists(this.destinationPath('config.json'))) {
      this.fs.move(this.destinationPath('config.json'), this.destinationPath(this.config.get('name') + '/config.json'));
    }
  }
}

module.exports = Generator;
module.exports.extractFromReadme = extractFromReadme;
<commit_msg>fix if empty<commit_after>'use strict';
const _ = require('lodash');
const Base = require('yeoman-generator').Base;
const known = require('../../utils/known');

function extractFromReadme(content) {
  const safe = (p) => p ? p[1] : '';
  // between header and installation
  const longDescription = safe(content.match(/=====$\s([\s\S]*)^Installation/m)).trim();
  // usage till end line
  const readme = safe(content.match(/(^Usage[\s\S]*)^\*\*\*$/m)).trim();

  return {longDescription, readme};
}

function toPhoveaName(name) {
  return name.replace(/^caleydo_/, 'phovea_');
}

function toExtension(name, desc) {
  const copy = _.merge({}, desc);
  delete copy.type;
  delete copy.id;
  delete copy.file;
  return {
    type: desc.type,
    id: desc.id || name,
    module: desc.file || '',
    extras: copy
  };
}

class Generator extends Base {

  constructor(args, options) {
    super(args, options);

    this.argument('type', {
      required: false
    });
  }

  initializing() {
    if (this.args.length === 0) {
      return this._promptForType().then(this._initializingImpl.bind(this));
    }
    this.type = this.args[0];
    return this._initializingImpl();
  }

  _promptForType() {
    return this.prompt({
      type: 'list',
      name: 'type',
      message: 'Plugin Type',
      choices: known.plugin.types,
      default: 'lib'
    }).then((props) => {
      this.type = props.type;
    });
  }

  _initializingImpl() {
    const pkg = this.fs.readJSON(this.destinationPath('package.json'));

    const {longDescription, readme} = extractFromReadme(this.fs.read(this.destinationPath('README.md')));

    this.props = {
      useDefaults: true,
      noSamples: true,
      description: (pkg.description || '').replace(/Caleydo Web/g, 'Phovea'),
      longDescription: longDescription.replace(/Caleydo Web/g, 'Phovea'),
      readme: readme.replace(/Caleydo Web/g, 'Phovea').replace(/\.\.\/caleydo_/g, 'phovea_'),
      authorEmail: 'contact@caleydo.org',
      authorUrl: 'https://caleydo.org'
    };
    const name = toPhoveaName(pkg.name);

    const safe = (obj, p, default_) => {
      var act = obj;
      for (let pi of p.split('.')) {
        if (!act) {
          return default_;
        }
        act = act[pi];
      }
      return act ? act : default_;
    };

    const validLib = (p) => {
      const r = known.lib.exists(p);
      if (!r) {
        this.log('ERROR: cant find lib: ', p);
        return false;
      }
      return true;
    };
    const validPlugin = (p) => {
      const r = known.plugin.exists(p);
      if (!r) {
        this.log('ERROR: cant find plugin: ', p);
        return false;
      }
      return true;
    };

    const libs = safe(pkg.caleydo, 'dependencies.web', {});

    const requirement2lib = {};
    known.lib.listServer.forEach((p) => {
      Object.keys(p.requirements).forEach((r) => {
        requirement2lib[r] = p;
      });
    });
    const knownRequirements = [].concat(...known.lib.listServer.map((m) => Object.keys(m.requirements)));
    const knownDebianPackages = [].concat(...known.lib.listServer.map((m) => Object.keys(m.debianPackages)));
    const knownRedhatPackages = [].concat(...known.lib.listServer.map((m) => Object.keys(m.redhatPackages)));

    const slibs = safe(pkg.caleydo, 'dependencies.python', {});
    const debianPackages = safe(pkg.caleydo, 'dependencies.debian', {});
    const redhatPackages = safe(pkg.caleydo, 'dependencies.redhat', {});

    this.config.defaults({
      type: this.type,
      name: name,
      author: 'The Caleydo Team',
      githubAccount: 'phovea',
      modules: Object.keys(pkg.peerDependencies || {}).map(toPhoveaName).filter(validPlugin),
      extensions: safe(pkg.caleydo, 'plugins.web', []).map(toExtension.bind(this, name)),
      sextensions: safe(pkg.caleydo, 'plugins.python', []).map(toExtension.bind(this, name)),

      // merge valid web libraries with valid looked up server libraries
      libraries: Object.keys(libs)
        .filter(validLib).concat(
          Object.keys(slibs).filter((d) => knownRequirements.indexOf(d) >= 0).map((d) => requirement2lib[d])),

      unknown: {
        // filter unknown and convert to the common format
        requirements: Object.keys(slibs).filter((d) => knownRequirements.indexOf(d) < 0).map((d) => d + slibs[d]),
        debianPackages: Object.keys(debianPackages).filter((d) => knownDebianPackages.indexOf(d) < 0).map((d) => d + debianPackages[d]),
        redhatPackages: Object.keys(redhatPackages).filter((d) => knownRedhatPackages.indexOf(d) < 0).map((d) => d + redhatPackages[d])
      }
    });
  }

  default() {
    this.composeWith('phovea:init-' + this.type, {
      options: this.props
    }, {
      local: require.resolve('../init-' + this.type)
    });
  }

  writing() {
    this.fs.delete(this.destinationPath('__index__.py'));
    this.fs.delete(this.destinationPath('.gitignore'));
    this.fs.delete(this.destinationPath('.npmignore'));
    this.fs.delete(this.destinationPath('.gitattributes'));
    this.fs.delete(this.destinationPath('LICENSE'));
    this.fs.delete(this.destinationPath('package.json'));

    this.fs.move(this.destinationPath('**.ts'), this.destinationPath('src/'));
    if (this.fs.exists(this.destinationPath('src/main.ts'))) {
      this.fs.move(this.destinationPath('src/main.ts'), this.destinationPath('src/index.ts'));
    }
    this.fs.move(this.destinationPath('*.scss'), this.destinationPath('src/'));
    this.fs.move(this.destinationPath('*.py'), this.destinationPath(this.config.get('name') + '/'));
    if (this.fs.exists(this.destinationPath('config.json'))) {
      this.fs.move(this.destinationPath('config.json'), this.destinationPath(this.config.get('name') + '/config.json'));
    }
  }
}

module.exports = Generator;
module.exports.extractFromReadme = extractFromReadme;
<|endoftext|>


<commit_before>'use strict';

let path = require('path');

class JbdsAutoInstallGenerator {
  constructor(jbdsInstallDir, jdkInstallDir) {
    this.autoInstall = this.generate(jbdsInstallDir, jdkInstallDir);
  }

  fileContent() {
    return this.autoInstall;
  }

  generate(jbdsInstallDir, jdkInstallDir) {
    let temp =
      [
        '<?xml version="1.0" encoding="UTF-8" standalone="no"?>',
        '<AutomatedInstallation langpack="eng">',
        '<com.jboss.devstudio.core.installer.HTMLInfoPanelWithRootWarning id="introduction"/>',
        '<com.izforge.izpack.panels.HTMLLicencePanel id="licence"/>',
        '<com.jboss.devstudio.core.installer.PathInputPanel id="target">',
        '<installpath>' + jbdsInstallDir + '</installpath>',
        '</com.jboss.devstudio.core.installer.PathInputPanel>',
        '<com.jboss.devstudio.core.installer.JREPathPanel id="jre"/>',
        '<com.jboss.devstudio.core.installer.JBossAsSelectPanel id="as">',
        '<installgroup>jbds</installgroup>',
        '</com.jboss.devstudio.core.installer.JBossAsSelectPanel>',
        '<com.jboss.devstudio.core.installer.InstallAdditionalFeaturesPanel id="features">',
        '<ius>com.jboss.devstudio.core.package,org.testng.eclipse.feature.group</ius>',
        '<locations>jbds</locations>',
        '</com.jboss.devstudio.core.installer.InstallAdditionalFeaturesPanel>',
        '<com.jboss.devstudio.core.installer.UpdatePacksPanel id="updatepacks"/>',
        '<com.jboss.devstudio.core.installer.DiskSpaceCheckPanel id="diskspacecheck"/>',
        '<com.izforge.izpack.panels.SummaryPanel id="summary"/>',
        '<com.izforge.izpack.panels.InstallPanel id="install"/>',
        '<com.jboss.devstudio.core.installer.CreateLinkPanel id="createlink">',
        '<jrelocation>' + path.join(jdkInstallDir, 'bin', 'javaw.exe') + '</jrelocation>',
        '</com.jboss.devstudio.core.installer.CreateLinkPanel>',
        '<com.izforge.izpack.panels.ShortcutPanel id="shortcut">',
        '<programGroup name="Red Hat JBoss Developer Studio 9"/>',
        '<shortcut KdeSubstUID="false" categories="" commandLine="" createForAll="false" description="Start Red Hat JBoss Developer Studio 9.1.0" encoding="" group="false" icon="' + path.join(jbdsInstallDir, 'studio', 'jbds.ico') + '" iconIndex="0" initialState="1" mimetype="" name="Red Hat JBoss Developer Studio 9.1.0.Beta1" target="' + path.join(jbdsInstallDir, 'studio', 'jbdevstudio.exe') + '" terminal="" terminalOptions="" tryexec="" type="3" url="" usertype="0" workingDirectory="' + path.join(jbdsInstallDir, 'studio') + '"/>',
        '<shortcut KdeSubstUID="false" categories="" commandLine="" createForAll="false" description="Start Red Hat JBoss Developer Studio 9.1.0" encoding="" group="true" icon="' + path.join(jbdsInstallDir, 'studio', 'jbds.ico') + '" iconIndex="0" initialState="1" mimetype="" name="Red Hat JBoss Developer Studio 9.1.0.Beta1" target="' + path.join(jbdsInstallDir, 'studio', 'jbdevstudio.exe') + '" terminal="" terminalOptions="" tryexec="" type="1" url="" usertype="0" workingDirectory="' + path.join(jbdsInstallDir, 'studio') + '"/>',
        '<shortcut KdeSubstUID="false" categories="" commandLine="-jar "' + path.join(jbdsInstallDir, 'Uninstaller', 'uninstaller.jar') + '"" createForAll="false" description="Uninstall Red Hat JBoss Developer Studio 9.1.0" encoding="" group="true" icon="' + path.join(jbdsInstallDir, 'studio', 'jbds_uninstall.ico') + '" iconIndex="0" initialState="1" mimetype="" name="Uninstall Red Hat JBoss Developer Studio 9.1.0.Beta1" target="' + path.join(jdkInstallDir, 'bin', 'javaw.exe') + '" terminal="" terminalOptions="" tryexec="" type="1" url="" usertype="0" workingDirectory=""/>',
        '</com.izforge.izpack.panels.ShortcutPanel>',
        '<com.jboss.devstudio.core.installer.ShortcutPanelPatch id="shortcutpatch"/>',
        '<com.izforge.izpack.panels.SimpleFinishPanel id="finish"/>',
        '</AutomatedInstallation>'
      ].join('\r\n');

      return temp;
  }
}
export default JbdsAutoInstallGenerator;
<commit_msg>JBDS-3776 use 9.1 as the version of JBDS (rather than a mix of 9.1, 9.1.0, and 9.1.0.Beta1)<commit_after>'use strict';

let path = require('path');

class JbdsAutoInstallGenerator {
  constructor(jbdsInstallDir, jdkInstallDir) {
    this.autoInstall = this.generate(jbdsInstallDir, jdkInstallDir);
  }

  fileContent() {
    return this.autoInstall;
  }

  generate(jbdsInstallDir, jdkInstallDir) {
    let jbdsVersion = "9.1";
    let temp =
      [
        '<?xml version="1.0" encoding="UTF-8" standalone="no"?>',
        '<AutomatedInstallation langpack="eng">',
        '<com.jboss.devstudio.core.installer.HTMLInfoPanelWithRootWarning id="introduction"/>',
        '<com.izforge.izpack.panels.HTMLLicencePanel id="licence"/>',
        '<com.jboss.devstudio.core.installer.PathInputPanel id="target">',
        '<installpath>' + jbdsInstallDir + '</installpath>',
        '</com.jboss.devstudio.core.installer.PathInputPanel>',
        '<com.jboss.devstudio.core.installer.JREPathPanel id="jre"/>',
        '<com.jboss.devstudio.core.installer.JBossAsSelectPanel id="as">',
        '<installgroup>jbds</installgroup>',
        '</com.jboss.devstudio.core.installer.JBossAsSelectPanel>',
        '<com.jboss.devstudio.core.installer.InstallAdditionalFeaturesPanel id="features">',
        '<ius>com.jboss.devstudio.core.package,org.testng.eclipse.feature.group</ius>',
        '<locations>jbds</locations>',
        '</com.jboss.devstudio.core.installer.InstallAdditionalFeaturesPanel>',
        '<com.jboss.devstudio.core.installer.UpdatePacksPanel id="updatepacks"/>',
        '<com.jboss.devstudio.core.installer.DiskSpaceCheckPanel id="diskspacecheck"/>',
        '<com.izforge.izpack.panels.SummaryPanel id="summary"/>',
        '<com.izforge.izpack.panels.InstallPanel id="install"/>',
        '<com.jboss.devstudio.core.installer.CreateLinkPanel id="createlink">',
        '<jrelocation>' + path.join(jdkInstallDir, 'bin', 'javaw.exe') + '</jrelocation>',
        '</com.jboss.devstudio.core.installer.CreateLinkPanel>',
        '<com.izforge.izpack.panels.ShortcutPanel id="shortcut">',
        '<programGroup name="Red Hat JBoss Developer Studio ' + jbdsVersion + '"/>',
        '<shortcut KdeSubstUID="false" categories="" commandLine="" createForAll="false" description="Start Red Hat JBoss Developer Studio ' + jbdsVersion + '" encoding="" group="false" icon="' + path.join(jbdsInstallDir, 'studio', 'jbds.ico') + '" iconIndex="0" initialState="1" mimetype="" name="Red Hat JBoss Developer Studio ' + jbdsVersion + '" target="' + path.join(jbdsInstallDir, 'studio', 'jbdevstudio.exe') + '" terminal="" terminalOptions="" tryexec="" type="3" url="" usertype="0" workingDirectory="' + path.join(jbdsInstallDir, 'studio') + '"/>',
        '<shortcut KdeSubstUID="false" categories="" commandLine="" createForAll="false" description="Start Red Hat JBoss Developer Studio ' + jbdsVersion + '" encoding="" group="true" icon="' + path.join(jbdsInstallDir, 'studio', 'jbds.ico') + '" iconIndex="0" initialState="1" mimetype="" name="Red Hat JBoss Developer Studio ' + jbdsVersion + '" target="' + path.join(jbdsInstallDir, 'studio', 'jbdevstudio.exe') + '" terminal="" terminalOptions="" tryexec="" type="1" url="" usertype="0" workingDirectory="' + path.join(jbdsInstallDir, 'studio') + '"/>',
        '<shortcut KdeSubstUID="false" categories="" commandLine="-jar "' + path.join(jbdsInstallDir, 'Uninstaller', 'uninstaller.jar') + '"" createForAll="false" description="Uninstall Red Hat JBoss Developer Studio ' + jbdsVersion + '" encoding="" group="true" icon="' + path.join(jbdsInstallDir, 'studio', 'jbds_uninstall.ico') + '" iconIndex="0" initialState="1" mimetype="" name="Uninstall Red Hat JBoss Developer Studio ' + jbdsVersion + '" target="' + path.join(jdkInstallDir, 'bin', 'javaw.exe') + '" terminal="" terminalOptions="" tryexec="" type="1" url="" usertype="0" workingDirectory=""/>',
        '</com.izforge.izpack.panels.ShortcutPanel>',
        '<com.jboss.devstudio.core.installer.ShortcutPanelPatch id="shortcutpatch"/>',
        '<com.izforge.izpack.panels.SimpleFinishPanel id="finish"/>',
        '</AutomatedInstallation>'
      ].join('\r\n');

      return temp;
  }
}
export default JbdsAutoInstallGenerator;
<|endoftext|>


<commit_before>'use strict';

var $ = require("jquery");
var Tone = require("Tone");
var synth = new Tone.SimpleSynth().toMaster();
var gl;
var THREE = require("three");
var scene, renderer, camera, cube;

function playArpeggio() {
  synth.triggerAttackRelease("A2", "8n",  "+4n * 0");
  synth.triggerAttackRelease("C#3", "8n", "+4n * 1");
  synth.triggerAttackRelease("E3", "8n",  "+4n * 2");
  synth.triggerAttackRelease("A3", "8n",  "+4n * 3");
  synth.triggerAttackRelease("C#4", "8n", "+4n * 4");
  synth.triggerAttackRelease("E4", "8n",  "+4n * 5");
  synth.triggerAttackRelease("A4", "8n",  "+4n * 6");
}

function initCubeScene() {
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

  renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  var geometry = new THREE.BoxGeometry( 1, 1, 1 );
  var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  cube = new THREE.Mesh( geometry, material );
  scene.add( cube );

  camera.position.z = 5;

  window.addEventListener('resize', function() {
    renderer.setSize(window.innerWidth, window.innerHeight);
  }, false);
}

function render() {
	requestAnimationFrame( render );

  cube.rotation.x += 0.1;
  cube.rotation.y += 0.1;

	renderer.render( scene, camera );
}

$(document).ready(function() {
  initCubeScene();
  render();
});
<commit_msg>Okay, nothings working yet, but I'm trying to understand mouse events and position<commit_after>'use strict';

var $ = require("jquery");
var Tone = require("Tone");
var synth = new Tone.SimpleSynth().toMaster();
var gl;
var THREE = require("three");
var scene, renderer, camera, cube;
var cubes = [];
var mouse_vector = new THREE.Vector3();

function playArpeggio() {
  synth.triggerAttackRelease("A2", "8n",  "+4n * 0");
  synth.triggerAttackRelease("C#3", "8n", "+4n * 1");
  synth.triggerAttackRelease("E3", "8n",  "+4n * 2");
  synth.triggerAttackRelease("A3", "8n",  "+4n * 3");
  synth.triggerAttackRelease("C#4", "8n", "+4n * 4");
  synth.triggerAttackRelease("E4", "8n",  "+4n * 5");
  synth.triggerAttackRelease("A4", "8n",  "+4n * 6");
}

function initCubeScene() {
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

  renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  var geometry = new THREE.BoxGeometry( 1, 1, 1 );
  var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  cube = new THREE.Mesh( geometry, material );
  scene.add( cube );
  cubes.push(cube);

  camera.position.z = 5;

  window.addEventListener('resize', function() {
    renderer.setSize(window.innerWidth, window.innerHeight);
  }, false);

  renderer.domElement.addEventListener('mousedown', handleClick);
}

function render() {
	requestAnimationFrame( render );

  for (var i=0; i<cubes.length; i++) {
    var cb = cubes[i];
    cb.rotation.x += 0.1;
    cb.rotation.y += 0.1;
  }

	renderer.render( scene, camera );
}

function addCube(vec) {
  var geometry = new THREE.BoxGeometry( 1, 1, 1 );
  var material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  var newcube = new THREE.Mesh(geometry, material);
  newcube.position.set(vec.x, vec.y, vec.z);
  newcube.__dirtyPosition = true;

  scene.add(newcube);
  cubes.push(newcube);
}

function handleClick(e) {
  e.preventDefault();
  var x = (e.clientX / window.innerWidth) * 2 - 1;
  var y = -(e.clientY / window.innerHeight) * 2 + 1;
  mouse_vector.set(x, y, 1);
  mouse_vector.project(camera);
  console.log(mouse_vector);

  addCube(mouse_vector);
}

$(document).ready(function() {
  initCubeScene();
  render();
});
<|endoftext|>


<commit_before>var GrovePi = require('node-grovepi').GrovePi;

 var GrovePiBoard = function() {
   console.log('GrovePiBoard.js: Constructor');
   this.results = this.init.apply(this);
   console.log('GrovePiBoard.js: Init Complete');
   console.log(this.results);

 };

 GrovePiBoard.prototype.init = function() {
   console.log('GrovePiBoard.js: Init Function');
   var board = new GrovePi.board({
     debug: true,
     onError: function(err){
       console.log('GrovePiBoard.js: Something went wrong');
       console.log(err)
     },
     onInit: function(res) {
       console.log('GrovePiBoard.js: GrovePi onInit');
       if(res){
         console.log('GrovePiBoard.js: GrovePi Version :: ' + board.version());

         // Get & init Digital inputs

         // Get & init Outputs
       } else {
         console.log('GrovePiBoard.js: No Res');
       }
     }
   });
   board.init();
   return board;
 };

 GrovePiBoard.prototype.registerSensor = function(sensorType, pin, repeat, callback){
   var sensor = new Sensor(sensorType, pin, repeat, callback);
   this.analogSensors.push(sensor);
   return sensor;
 }

module.exports = GrovePiBoard;

var Sensor = function(type, pin, repeat, callback) {
  this.pin = pin;
  this.repeat = repeat;
  this.callback = callback;
    if(type == 'analog'){

    } else if(type == 'digital'){

    }
};

Sensor.prototype.unregister = function(callback){
    clearInterval(this.testTimer);
    callback();
};

 // var Commands = GrovePi.commands;
 // var Board = GrovePi.board;
 // var LightAnalogSensor = GrovePi.sensors.LightAnalog;
 //
 // var board = new Board({
 //   debug: true,
 //   onError: function(err){
 //     console.log('GrovePiLightSensorNode: Something went wrong');
 //     console.log(err);
 //   },
 //   onInit: function(res) {
 //     if(res) {
 //       var lightSensor = new LightAnalogSensor(2);
 //       console.log('Light Analog Sensor (start watch)');
 //       lightSensor.on('change', function(res) {
 //         console.log('Light onChange value=' + res);
 //         var msg = {};
 //         msg.payload = res;
 //         node.send(msg);
 //       })
 //     }
 //   }
 // });
 // board.init();
<commit_msg>Fixing Init State<commit_after>var GrovePi = require('node-grovepi').GrovePi;

var STATE_UNINITIALISED = 0;
var STATE_INITIALISED   = 1;

 var GrovePiBoard = function() {
   console.log('GrovePiBoard.js: Constructor');
   this.state = this.state || STATE_UNINITIALISED;
   console.log('GrovePiBoard.js: State: ' + this.state);
   if(this.state == STATE_UNINITIALISED){
     this.board = this.init.apply(this);
     this.state = STATE_INITIALISED;
   }
   console.log('GrovePiBoard.js: Init Complete');
   console.log(this.board);

 };

 GrovePiBoard.prototype.init = function() {
   console.log('GrovePiBoard.js: Init Function');
   var board = new GrovePi.board({
     debug: true,
     onError: function(err){
       console.log('GrovePiBoard.js: Something went wrong');
       console.log(err)
     },
     onInit: function(res) {
       console.log('GrovePiBoard.js: GrovePi onInit');
       if(res){
         console.log('GrovePiBoard.js: GrovePi Version :: ' + board.version());

         // Get & init Digital inputs

         // Get & init Outputs
       } else {
         console.log('GrovePiBoard.js: No Res');
       }
     }
   });
   board.init();
   return board;
 };

 GrovePiBoard.prototype.registerSensor = function(sensorType, pin, repeat, callback){
   var sensor = new Sensor(sensorType, pin, repeat, callback);
   this.analogSensors.push(sensor);
   return sensor;
 }

module.exports = GrovePiBoard;

var Sensor = function(type, pin, repeat, callback) {
  this.pin = pin;
  this.repeat = repeat;
  this.callback = callback;
    if(type == 'analog'){

    } else if(type == 'digital'){

    }
};

Sensor.prototype.unregister = function(callback){
    clearInterval(this.testTimer);
    callback();
};

 // var Commands = GrovePi.commands;
 // var Board = GrovePi.board;
 // var LightAnalogSensor = GrovePi.sensors.LightAnalog;
 //
 // var board = new Board({
 //   debug: true,
 //   onError: function(err){
 //     console.log('GrovePiLightSensorNode: Something went wrong');
 //     console.log(err);
 //   },
 //   onInit: function(res) {
 //     if(res) {
 //       var lightSensor = new LightAnalogSensor(2);
 //       console.log('Light Analog Sensor (start watch)');
 //       lightSensor.on('change', function(res) {
 //         console.log('Light onChange value=' + res);
 //         var msg = {};
 //         msg.payload = res;
 //         node.send(msg);
 //       })
 //     }
 //   }
 // });
 // board.init();
<|endoftext|>


<commit_before>// JavaScript Document

// Scripts written by YOURNAME @ YOURCOMPANY

// Inspired by https://medium.com/outsystems-experts/gestures-glamour-setting-up-a-touch-menu-6d9b94039997#.d2r8ubylw

document.addEventListener("DOMContentLoaded", () => {
    const menu_container      = document.querySelector(".navigation-block.-flyout");
    const menu                = document.querySelector(".navigation_inner");
    const overlay             = document.querySelector(".navigation_background");
    const toggle              = document.querySelector(".menu-toggle");
    const active_class        = "is-active";
    const transitioning_class = "is-transitioning";
    const maxOpacity          = 0.5; // if changed, don't forget to change opacity in css
    const velocity            = 0.3;

    let trackable_element     = false;
    let touching_element      = false;
    let start_time            = 0;
    let start_coords          = [0, 0];
    let current_coords        = [0, 0];

    let is_open               = false;
    let is_moving             = false;
    let menu_width            = 0;
    let last_coords           = [0, 0];
    let move_x                = 0; // where the menu currently
    let drag_direction        = "";

    const focusTrapper = focusTrap(".navigation-block.-flyout");

    const close_menu = (translate_x) => {
        focusTrapper.deactivate();

        const on_transition_end = () => {
            overlay.style.opacity = "";

            menu_container.removeEventListener("transitionend", on_transition_end, false);
        };

        if (translate_x < 0 || !is_open) {
            menu.style.transform = "";
            menu.style.webkitTransform = "";

            overlay.classList.remove(active_class);

            menu_container.classList.remove(active_class);
            menu_container.addEventListener("transitionend", on_transition_end, false);
        }
    };

    const open_menu = () => {
        menu.style.transform = "";
        menu.style.webkitTransform = "";

        menu_container.classList.add(active_class);

        overlay.classList.add(active_class);
        overlay.style.opacity = "";

        focusTrapper.activate();
    };

    const close_menu_overlay = () => {
        focusTrapper.deactivate();

        const on_transition_end = () => {
            overlay.classList.remove(active_class);

            menu_container.removeEventListener("transitionend", on_transition_end);
        };

        menu_container.addEventListener("transitionend", on_transition_end, false);
        menu_container.classList.remove(active_class);
    };

    const click_open_menu = () => {
        overlay.classList.add(active_class);

        requestAnimationFrame(() => {
            setTimeout(() => {
                menu_container.classList.add(active_class);
                menu_container.focus();
                focusTrapper.activate();
            }, 1);
        });
    };

    const update_ui = () => {
        if (is_moving) {
            menu.style.transform = "translateX(" + move_x + "px)";
            menu.style.webkitTransform = "translateX(" + move_x + "px)";

            requestAnimationFrame(update_ui);
        }
    };

    const toggle_transitions = (elem, mode = 0) => {
        if (mode === 1) {
            elem.style.transition = "";
        } else {
            elem.style.transition = "none";
        }
    };

    const touch_start = (start_coords) => {
        const menu_open = menu_container.classList.contains(active_class);

        if (menu_open !== false) {
            is_open = true;
        } else {
            is_open = false;
        }

        // disable transitions
        toggle_transitions(menu_container);
        toggle_transitions(menu);

        is_moving   = true;
        menu_width  = menu.offsetWidth;
        last_coords = start_coords;

        if (is_open) {
            move_x = 0;
        } else {
            move_x = -menu_width;
        }

        menu_container.classList.add(transitioning_class);

        overlay.classList.add(active_class);

        drag_direction = "";
    };

    const touch_move = (event, current_coords, translate_coords) => {
        if (!drag_direction) {
            if (Math.abs(translate_coords[0]) >= Math.abs(translate_coords[1])) {
                drag_direction = "horizontal";
            } else {
                drag_direction = "vertical";
            }

            requestAnimationFrame(update_ui); // this is what effectively does the animation (ﾉ◕ヮ◕)ﾉ*:・ﾟ✧
        }
        if (drag_direction === "vertical") {
            last_coords = current_coords;
        } else {
            event.preventDefault();

            if (move_x + (current_coords[0] - last_coords[0]) < 0 && move_x + (current_coords[0] - last_coords[0]) > -menu_width) {
                move_x = move_x + (current_coords[0] - last_coords[0]);
            }

            last_coords = current_coords;

            // disable transitions
            toggle_transitions(overlay);

            const newOpacity = (((maxOpacity) * (100 - ((Math.abs(move_x) * 100) / menu_width))) / 100);

            if (overlay.style.opacity !== newOpacity.toFixed(2) && newOpacity.toFixed(1) % 1 !== 0) {
                overlay.style.opacity = newOpacity.toFixed(2);
            }
        }
    };

    const touch_end = (current_coords, translate_coords, time_taken) => {
        is_moving = false;

        if (current_coords === [0, 0]) {
            // enable transitions
            toggle_transitions(menu_container, 1);

            if (is_open) {
                toggle_transitions(menu, 1);
            } else {
                toggle_transitions(overlay, 1);
            }
        } else {
            if (is_open) {
                if ((translate_coords[0] < (-menu_width) / 2) || (Math.abs(translate_coords[0]) / time_taken > velocity)) {
                    close_menu(translate_coords[0]);
                    is_open = false;
                } else {
                    open_menu();
                    is_open = true;
                }
            } else {
                if (translate_coords[0] > menu_width / 2 || (Math.abs(translate_coords[0]) / time_taken > velocity)) {
                    open_menu();
                    is_open = true;
                } else {
                    close_menu(translate_coords[0]);
                    is_open = false;
                }

            }
        }

        menu_container.classList.remove(transitioning_class);

        // enable transitions
        toggle_transitions(menu_container, 1);
        toggle_transitions(menu, 1);
        toggle_transitions(overlay, 1);
    };

    const on_touch_start = (event) => {
        let element      = document.elementFromPoint(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
        let is_clickable = false;

        if (element) {
            while (element.parentNode) {
                if (element.classList.contains("menu-list_toggle") || element.classList.contains("menu-list_link") || element.classList.contains("search-form_container")) {
                    is_clickable = true; return;
                }

                element = element.parentNode;
            }
        }

        if (is_clickable) {
            return;
        }

        start_time = new Date().getTime();
        start_coords = [event.touches[0].pageX, event.touches[0].pageY];

        touching_element = true;

        touch_start(start_coords);
    };

    const on_touch_move = (event) => {
        let element      = document.elementFromPoint(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
        let is_clickable = false;

        if (element) {
            while (element.parentNode) {
                if (element.classList.contains("menu-list_toggle") || element.classList.contains("menu-list_link") || element.classList.contains("search-form_container")) {
                    is_clickable = true; return;
                }

                element = element.parentNode;
            }
        }

        if (!touching_element || is_clickable) {
            return;
        }

        current_coords          = [event.touches[0].pageX, event.touches[0].pageY];
        const translate_coords  = [(current_coords[0] - start_coords[0]), (current_coords[1] - start_coords[1])];

        touch_move(event, current_coords, translate_coords);
    };

    const on_touch_end = (event) => {
        let element      = document.elementFromPoint(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
        let is_clickable = false;

        if (element) {
            while (element.parentNode) {
                if (element.classList.contains("menu-list_toggle") || element.classList.contains("menu-list_link") || element.classList.contains("search-form_container")) {
                    is_clickable = true; return;
                }

                element = element.parentNode;
            }
        }

        if (!touching_element || is_clickable) {
            return;
        }

        touching_element = false;

        const translate_coords = [(current_coords[0] - start_coords[0]), (current_coords[1] - start_coords[1])];

        const time_taken = (new Date().getTime() - start_time);

        touch_end(current_coords, translate_coords, time_taken);
    };

    const init = (element) => {
        trackable_element = element;

        start_time = new Date().getTime(); // start time of the touch

        trackable_element.addEventListener("touchstart", on_touch_start, false);
        trackable_element.addEventListener("touchmove", on_touch_move, false);
        trackable_element.addEventListener("touchend", on_touch_end, false);

        overlay.addEventListener("click", close_menu_overlay, false); // click the overlay to immediately close the menu
        toggle.addEventListener("click", click_open_menu, false);     // click the toggle to immediately open the menu
    };

    init(menu);
});
<commit_msg>Improve touch functions to prevent clickable items from closing the menu<commit_after>// JavaScript Document

// Scripts written by YOURNAME @ YOURCOMPANY

// Inspired by https://medium.com/outsystems-experts/gestures-glamour-setting-up-a-touch-menu-6d9b94039997#.d2r8ubylw

document.addEventListener("DOMContentLoaded", () => {
    const menu_container      = document.querySelector(".navigation-block.-flyout");
    const menu                = document.querySelector(".navigation_inner");
    const overlay             = document.querySelector(".navigation_background");
    const toggle              = document.querySelector(".menu-toggle");
    const active_class        = "is-active";
    const transitioning_class = "is-transitioning";
    const maxOpacity          = 0.5; // if changed, don't forget to change opacity in css
    const velocity            = 0.3;

    let trackable_element     = false;
    let touching_element      = false;
    let start_time            = 0;
    let start_coords          = [0, 0];
    let current_coords        = [0, 0];

    let is_open               = false;
    let is_moving             = false;
    let menu_width            = 0;
    let last_coords           = [0, 0];
    let move_x                = 0; // where the menu currently
    let drag_direction        = "";

    const focusTrapper = focusTrap(".navigation-block.-flyout");

    const close_menu = (translate_x) => {
        focusTrapper.deactivate();

        const on_transition_end = () => {
            overlay.style.opacity = "";

            menu_container.removeEventListener("transitionend", on_transition_end, false);
        };

        if (translate_x < 0 || !is_open) {
            menu.style.transform = "";
            menu.style.webkitTransform = "";

            overlay.classList.remove(active_class);

            menu_container.classList.remove(active_class);
            menu_container.addEventListener("transitionend", on_transition_end, false);
        }
    };

    const open_menu = () => {
        menu.style.transform = "";
        menu.style.webkitTransform = "";

        menu_container.classList.add(active_class);

        overlay.classList.add(active_class);
        overlay.style.opacity = "";

        focusTrapper.activate();
    };

    const close_menu_overlay = () => {
        focusTrapper.deactivate();

        const on_transition_end = () => {
            overlay.classList.remove(active_class);

            menu_container.removeEventListener("transitionend", on_transition_end);
        };

        menu_container.addEventListener("transitionend", on_transition_end, false);
        menu_container.classList.remove(active_class);
    };

    const click_open_menu = () => {
        overlay.classList.add(active_class);

        requestAnimationFrame(() => {
            setTimeout(() => {
                menu_container.classList.add(active_class);
                menu_container.focus();
                focusTrapper.activate();
            }, 1);
        });
    };

    const update_ui = () => {
        if (is_moving) {
            menu.style.transform = "translateX(" + move_x + "px)";
            menu.style.webkitTransform = "translateX(" + move_x + "px)";

            requestAnimationFrame(update_ui);
        }
    };

    const toggle_transitions = (elem, mode = 0) => {
        if (mode === 1) {
            elem.style.transition = "";
        } else {
            elem.style.transition = "none";
        }
    };

    const touch_start = (start_coords) => {
        const menu_open = menu_container.classList.contains(active_class);

        if (menu_open !== false) {
            is_open = true;
        } else {
            is_open = false;
        }

        // disable transitions
        toggle_transitions(menu_container);
        toggle_transitions(menu);

        is_moving   = true;
        menu_width  = menu.offsetWidth;
        last_coords = start_coords;

        if (is_open) {
            move_x = 0;
        } else {
            move_x = -menu_width;
        }

        menu_container.classList.add(transitioning_class);

        overlay.classList.add(active_class);

        drag_direction = "";
    };

    const touch_move = (event, current_coords, translate_coords) => {
        if (!drag_direction) {
            if (Math.abs(translate_coords[0]) >= Math.abs(translate_coords[1])) {
                drag_direction = "horizontal";
            } else {
                drag_direction = "vertical";
            }

            requestAnimationFrame(update_ui); // this is what effectively does the animation (ﾉ◕ヮ◕)ﾉ*:・ﾟ✧
        }
        if (drag_direction === "vertical") {
            last_coords = current_coords;
        } else {
            event.preventDefault();

            if (move_x + (current_coords[0] - last_coords[0]) < 0 && move_x + (current_coords[0] - last_coords[0]) > -menu_width) {
                move_x = move_x + (current_coords[0] - last_coords[0]);
            }

            last_coords = current_coords;

            // disable transitions
            toggle_transitions(overlay);

            const newOpacity = (((maxOpacity) * (100 - ((Math.abs(move_x) * 100) / menu_width))) / 100);

            if (overlay.style.opacity !== newOpacity.toFixed(2) && newOpacity.toFixed(1) % 1 !== 0) {
                overlay.style.opacity = newOpacity.toFixed(2);
            }
        }
    };

    const touch_end = (current_coords, translate_coords, time_taken) => {
        is_moving = false;

        if (current_coords === [0, 0]) {
            // enable transitions
            toggle_transitions(menu_container, 1);

            if (is_open) {
                toggle_transitions(menu, 1);
            } else {
                toggle_transitions(overlay, 1);
            }
        } else {
            if (is_open) {
                if ((translate_coords[0] < (-menu_width) / 2) || (Math.abs(translate_coords[0]) / time_taken > velocity)) {
                    close_menu(translate_coords[0]);
                    is_open = false;
                } else {
                    open_menu();
                    is_open = true;
                }
            } else {
                if (translate_coords[0] > menu_width / 2 || (Math.abs(translate_coords[0]) / time_taken > velocity)) {
                    open_menu();
                    is_open = true;
                } else {
                    close_menu(translate_coords[0]);
                    is_open = false;
                }

            }
        }

        menu_container.classList.remove(transitioning_class);

        // enable transitions
        toggle_transitions(menu_container, 1);
        toggle_transitions(menu, 1);
        toggle_transitions(overlay, 1);
    };

    const on_touch_start = (event) => {
        let element      = document.elementFromPoint(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
        let is_clickable = false;

        if (element) {
            while (element.parentNode) {
                if ((element.tagName === "A" || element.tagName === "BUTTON" || element.tagName === "INPUT") && element != overlay) {
                    is_clickable = true; return;
                }

                element = element.parentNode;
            }
        }

        if (is_clickable) {
            return;
        }

        start_time = new Date().getTime();
        start_coords = [event.touches[0].pageX, event.touches[0].pageY];

        touching_element = true;

        touch_start(start_coords);
    };

    const on_touch_move = (event) => {
        let element      = document.elementFromPoint(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
        let is_clickable = false;

        if (element) {
            while (element.parentNode) {
                if ((element.tagName === "A" || element.tagName === "BUTTON" || element.tagName === "INPUT") && element != overlay) {
                    is_clickable = true; return;
                }

                element = element.parentNode;
            }
        }

        if (!touching_element || is_clickable) {
            return;
        }

        current_coords          = [event.touches[0].pageX, event.touches[0].pageY];
        const translate_coords  = [(current_coords[0] - start_coords[0]), (current_coords[1] - start_coords[1])];

        touch_move(event, current_coords, translate_coords);
    };

    const on_touch_end = (event) => {
        let element      = document.elementFromPoint(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
        let is_clickable = false;

        if (element) {
            while (element.parentNode) {
                if ((element.tagName === "A" || element.tagName === "BUTTON" || element.tagName === "INPUT") && element != overlay) {
                    is_clickable = true; return;
                }

                element = element.parentNode;
            }
        }

        if (!touching_element || is_clickable) {
            return;
        }

        touching_element = false;

        const translate_coords = [(current_coords[0] - start_coords[0]), (current_coords[1] - start_coords[1])];

        const time_taken = (new Date().getTime() - start_time);

        touch_end(current_coords, translate_coords, time_taken);
    };

    const init = (element) => {
        trackable_element = element;

        start_time = new Date().getTime(); // start time of the touch

        trackable_element.addEventListener("touchstart", on_touch_start, false);
        trackable_element.addEventListener("touchmove", on_touch_move, false);
        trackable_element.addEventListener("touchend", on_touch_end, false);

        overlay.addEventListener("click", close_menu_overlay, false); // click the overlay to immediately close the menu
        toggle.addEventListener("click", click_open_menu, false);     // click the toggle to immediately open the menu
    };

    init(menu);
});
<|endoftext|>


<commit_before>// this is the router that instructs the server 'what to do' depending on which endpoint
const express = require('express');
const googleController = require('./googleController');
const router = express.Router();

//in the future we can do (/'endpoint', check Redis for result, googleAPIController)
router.get('/museum', (req, res) => {
  // console.log('look for coordinates in here', req);
  googleController.getMuseumData(37, -122, (data) =>{
    console.log('answer', data);
    if (data === null) {
      res.status(204).send('our response');
    } else {
      console.log('our response');
      res.status(200).json(data);
    }
  });
});

module.exports = router;<commit_msg>clean up response code, hard code in example, until client sends location<commit_after>// this is the router that instructs the server 'what to do' depending on which endpoint
const express = require('express');
const googleController = require('./googleController');
const router = express.Router();

//in the future we can do (/'endpoint', check Redis for result, googleAPIController)
router.get('/museum', (req, res) => {
  // console.log('look for coordinates in here', req);
  googleController.getMuseumData(37.7825177, -122.4106772, (data) =>{
    console.log('answer', data);
    if (data === null) {
      res.status(204).end();
    } else {
      console.log('our response');
      res.status(200).json(data);
    }
  });
});

module.exports = router;<|endoftext|>


<commit_before>/*
 * Kuzzle, a backend software, self-hostable and ready to use
 * to power modern apps
 *
 * Copyright 2015-2017 Kuzzle
 * mailto: support AT kuzzle.io
 * website: http://kuzzle.io
 *
 * 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
 *
 * https://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';

const
  Bluebird = require('bluebird'),
  KuzzleInternalError = require('kuzzle-common-objects').errors.InternalError,
  crypto = require('crypto');

const
  lockId = 'bootstrap-lock',
  jwtSecretId = 'security.jwt.secret';

class InternalEngineBootstrap {
  /**
   * @param kuzzle
   * @param engine {InternalEngine}
   * @constructor
   */
  constructor (kuzzle, engine) {
    this.kuzzle = kuzzle;
    this.db = engine || this.kuzzle.internalEngine;
  }

  /**
   * Bootstraps Kuzzle storage engine
   * Creates the internal index and collections if needed
   */
  * _allGen () {
    const isLocked = yield this.lock();

    if (isLocked) {
      yield this.getJWTSecret();
      return this._waitTillUnlocked();
    }

    yield this.db.createInternalIndex();
    yield this.createCollections();
    yield this.getJWTSecret();
    yield this.db.refresh();

    this.kuzzle.indexCache.add(this.db.index);

    yield this.unLock();

    return Bluebird.resolve();
  }

  createCollections () {
    return this.createPluginsCollection()
      .then(() => this.createRolesCollection())
      .then(() => this.createProfilesCollection())
      .then(() => this.createUsersCollection())
      .then(() => this.createValidationCollection(this.kuzzle.config.validation));
  }

  createRolesCollection () {
    if (this.kuzzle.indexCache.exists(this.db.index, 'roles')) {
      return Bluebird.resolve();
    }

    const mapping = {
      properties: {
        controllers: {
          enabled: false
        }
      }
    };

    return this.db.updateMapping('roles', mapping)
      .then(() => {
        const promises = ['anonymous', 'default', 'admin']
          .map(roleId => this.db.createOrReplace('roles', roleId, this.kuzzle.config.security.default.role));

        this.kuzzle.indexCache.add(this.db.index, 'roles');

        return Bluebird.all(promises);
      });
  }

  createPluginsCollection () {
    if (this.kuzzle.indexCache.exists(this.db.index, 'plugins')) {
      return Bluebird.resolve();
    }

    return this.db.updateMapping('plugins', {
      properties: {
        config: {
          enabled: false
        }
      }
    });
  }

  createProfilesCollection () {
    if (this.kuzzle.indexCache.exists(this.db.index, 'profiles')) {
      return Bluebird.resolve();
    }

    const mapping = {
      properties: {
        policies: {
          properties: {
            roleId: {
              type: 'keyword'
            }
          }
        }
      }
    };

    return this.db.updateMapping('profiles', mapping)
      .then(() => {
        this.kuzzle.indexCache.add(this.db.index, 'profiles');

        const promises = ['default', 'anonymous', 'admin'].map(profileId => {
          return this.db.createOrReplace('profiles', profileId, {
            policies: [{roleId: profileId}]
          });
        });

        return Bluebird.all(promises);
      });
  }

  createUsersCollection () {
    if (this.kuzzle.indexCache.exists(this.db.index, 'users')) {
      return Bluebird.resolve();
    }

    const mapping = {
      properties: {
        profileIds: {
          type: 'keyword'
        }
      }
    };

    return this.db.updateMapping('users', mapping)
      .then(() => {
        this.kuzzle.indexCache.add(this.db.index, 'users');
      });
  }

  createValidationCollection (validationConfiguration) {
    if (this.kuzzle.indexCache.exists(this.db.index, 'validations')) {
      return Bluebird.resolve();
    }

    this.kuzzle.pluginsManager.trigger('log:info', '== Creating validation collection...');

    return this.db.updateMapping('validations', {
      properties: {
        index: {
          type: 'keyword'
        },
        collection: {
          type: 'keyword'
        },
        validation: {
          enabled: false
        }
      }
    }).then(() => {
      if (validationConfiguration) {
        const promises = [];

        Object.keys(validationConfiguration).forEach(indexName => {
          Object.keys(validationConfiguration[indexName]).forEach(collectionName => {
            // createOrReplace instead of create to avoid mess on concurency
            // TODO fix with a lock instead
            promises.push(this.kuzzle.internalEngine.createOrReplace('validations', `${indexName}#${collectionName}`, {
              index: indexName,
              collection: collectionName,
              validation: validationConfiguration[indexName][collectionName]
            }));
          });
        });

        return Bluebird.all(promises);
      }

      return Bluebird.resolve();
    })
      .then(() => {
        this.kuzzle.indexCache.add(this.db.index, 'validations');
      });
  }

  * _getJWTSecretGen () {
    if (this.kuzzle.config.security.jwt.secret !== null) {
      return this.kuzzle.config.security.jwt.secret;
    }

    // try to create first to avoid collisions
    try {
      const seed = crypto.randomBytes(512).toString('hex');
      yield this.db.create('config', jwtSecretId, {seed});
      this.kuzzle.config.security.jwt.secret = seed;
    }
    catch(e) {
      const response = yield this.db.get('config', jwtSecretId);
      this.kuzzle.config.security.jwt.secret = response._source.seed;
    }
  }

  adminExists () {
    return this.db.search('users', {query: {terms: {profileIds: ['admin']}}}, {from: 0, size: 0})
      .then(response => (response.total > 0));
  }

  /**
   * Checks if Kuzzle is already being bootstraped.
   * If not set a lock.
   * Returns true if the bootstrap is locked, false otherwise.
   *
   * @generator
   * @private
   * @returns {boolean}
   */
  * _lockGen () {
    let lock;

    try {
      yield this.db.create('config', lockId, {timestamp: Date.now()});
      return false;
    }
    catch (e) {
      // lock exists - try to get it and check if it is old enough to erase it
    }

    lock = yield this.db.get('config', lockId);
    if (lock._source.timestamp < Date.now() - 30000) {
      yield this.db.createOrReplace('config', lockId, {timestamp: Date.now()});
      return false;
    }

    return true;
  }

  unLock () {
    return this.db.delete('config', lockId);
  }

  _waitTillUnlocked (attempts = 0) {
    return this.db.exists('config', lockId)
      .then(isLocked => {
        if (!isLocked) {
          return;
        }

        if (attempts > 10) {
          throw new KuzzleInternalError('Internal engine bootstrap - lock wait timeout exceeded');
        }

        return Bluebird.delay(Math.round(this.kuzzle.config.services.internalEngine.bootstrapLockTimeout / 10))
          .then(() => this._waitTillUnlocked(attempts + 1));
      });

  }
}

InternalEngineBootstrap.prototype.all = Bluebird.coroutine(InternalEngineBootstrap.prototype._allGen);

InternalEngineBootstrap.prototype.getJWTSecret = Bluebird.coroutine(InternalEngineBootstrap.prototype._getJWTSecretGen);

InternalEngineBootstrap.prototype.lock = Bluebird.coroutine(InternalEngineBootstrap.prototype._lockGen);

module.exports = InternalEngineBootstrap;
<commit_msg>remove promise warnings from the internal engine's bootstrap<commit_after>/*
 * Kuzzle, a backend software, self-hostable and ready to use
 * to power modern apps
 *
 * Copyright 2015-2017 Kuzzle
 * mailto: support AT kuzzle.io
 * website: http://kuzzle.io
 *
 * 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
 *
 * https://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';

const
  Bluebird = require('bluebird'),
  KuzzleInternalError = require('kuzzle-common-objects').errors.InternalError,
  crypto = require('crypto');

const
  lockId = 'bootstrap-lock',
  jwtSecretId = 'security.jwt.secret';

class InternalEngineBootstrap {
  /**
   * @param kuzzle
   * @param engine {InternalEngine}
   * @constructor
   */
  constructor (kuzzle, engine) {
    this.kuzzle = kuzzle;
    this.db = engine || this.kuzzle.internalEngine;
  }

  /**
   * Bootstraps Kuzzle storage engine
   * Creates the internal index and collections if needed
   */
  * _allGen () {
    const isLocked = yield this.lock();

    if (isLocked) {
      yield this.getJWTSecret();
      return this._waitTillUnlocked();
    }

    yield this.db.createInternalIndex();
    yield this.createCollections();
    yield this.getJWTSecret();
    yield this.db.refresh();

    this.kuzzle.indexCache.add(this.db.index);

    yield this.unLock();

    return Bluebird.resolve();
  }

  createCollections () {
    return this.createPluginsCollection()
      .then(() => this.createRolesCollection())
      .then(() => this.createProfilesCollection())
      .then(() => this.createUsersCollection())
      .then(() => this.createValidationCollection(this.kuzzle.config.validation));
  }

  createRolesCollection () {
    if (this.kuzzle.indexCache.exists(this.db.index, 'roles')) {
      return Bluebird.resolve();
    }

    const mapping = {
      properties: {
        controllers: {
          enabled: false
        }
      }
    };

    return this.db.updateMapping('roles', mapping)
      .then(() => {
        const promises = ['anonymous', 'default', 'admin']
          .map(roleId => this.db.createOrReplace('roles', roleId, this.kuzzle.config.security.default.role));

        this.kuzzle.indexCache.add(this.db.index, 'roles');

        return Bluebird.all(promises);
      });
  }

  createPluginsCollection () {
    if (this.kuzzle.indexCache.exists(this.db.index, 'plugins')) {
      return Bluebird.resolve();
    }

    return this.db.updateMapping('plugins', {
      properties: {
        config: {
          enabled: false
        }
      }
    });
  }

  createProfilesCollection () {
    if (this.kuzzle.indexCache.exists(this.db.index, 'profiles')) {
      return Bluebird.resolve();
    }

    const mapping = {
      properties: {
        policies: {
          properties: {
            roleId: {
              type: 'keyword'
            }
          }
        }
      }
    };

    return this.db.updateMapping('profiles', mapping)
      .then(() => {
        this.kuzzle.indexCache.add(this.db.index, 'profiles');

        const promises = ['default', 'anonymous', 'admin'].map(profileId => {
          return this.db.createOrReplace('profiles', profileId, {
            policies: [{roleId: profileId}]
          });
        });

        return Bluebird.all(promises);
      });
  }

  createUsersCollection () {
    if (this.kuzzle.indexCache.exists(this.db.index, 'users')) {
      return Bluebird.resolve();
    }

    const mapping = {
      properties: {
        profileIds: {
          type: 'keyword'
        }
      }
    };

    return this.db.updateMapping('users', mapping)
      .then(() => this.kuzzle.indexCache.add(this.db.index, 'users'));
  }

  createValidationCollection (validationConfiguration) {
    if (this.kuzzle.indexCache.exists(this.db.index, 'validations')) {
      return Bluebird.resolve();
    }

    this.kuzzle.pluginsManager.trigger('log:info', '== Creating validation collection...');

    return this.db.updateMapping('validations', {
      properties: {
        index: {
          type: 'keyword'
        },
        collection: {
          type: 'keyword'
        },
        validation: {
          enabled: false
        }
      }
    }).then(() => {
      if (validationConfiguration) {
        const promises = [];

        Object.keys(validationConfiguration).forEach(indexName => {
          Object.keys(validationConfiguration[indexName]).forEach(collectionName => {
            // createOrReplace instead of create to avoid mess on concurency
            // TODO fix with a lock instead
            promises.push(this.kuzzle.internalEngine.createOrReplace('validations', `${indexName}#${collectionName}`, {
              index: indexName,
              collection: collectionName,
              validation: validationConfiguration[indexName][collectionName]
            }));
          });
        });

        return Bluebird.all(promises);
      }

      return null;
    })
      .then(() => this.kuzzle.indexCache.add(this.db.index, 'validations'));
  }

  * _getJWTSecretGen () {
    if (this.kuzzle.config.security.jwt.secret !== null) {
      return this.kuzzle.config.security.jwt.secret;
    }

    // try to create first to avoid collisions
    try {
      const seed = crypto.randomBytes(512).toString('hex');
      yield this.db.create('config', jwtSecretId, {seed});
      this.kuzzle.config.security.jwt.secret = seed;
    }
    catch(e) {
      const response = yield this.db.get('config', jwtSecretId);
      this.kuzzle.config.security.jwt.secret = response._source.seed;
    }
  }

  adminExists () {
    return this.db.search('users', {query: {terms: {profileIds: ['admin']}}}, {from: 0, size: 0})
      .then(response => (response.total > 0));
  }

  /**
   * Checks if Kuzzle is already being bootstraped.
   * If not set a lock.
   * Returns true if the bootstrap is locked, false otherwise.
   *
   * @generator
   * @private
   * @returns {boolean}
   */
  * _lockGen () {
    let lock;

    try {
      yield this.db.create('config', lockId, {timestamp: Date.now()});
      return false;
    }
    catch (e) {
      // lock exists - try to get it and check if it is old enough to erase it
    }

    lock = yield this.db.get('config', lockId);
    if (lock._source.timestamp < Date.now() - 30000) {
      yield this.db.createOrReplace('config', lockId, {timestamp: Date.now()});
      return false;
    }

    return true;
  }

  unLock () {
    return this.db.delete('config', lockId);
  }

  _waitTillUnlocked (attempts = 0) {
    return this.db.exists('config', lockId)
      .then(isLocked => {
        if (!isLocked) {
          return;
        }

        if (attempts > 10) {
          throw new KuzzleInternalError('Internal engine bootstrap - lock wait timeout exceeded');
        }

        return Bluebird.delay(Math.round(this.kuzzle.config.services.internalEngine.bootstrapLockTimeout / 10))
          .then(() => this._waitTillUnlocked(attempts + 1));
      });

  }
}

InternalEngineBootstrap.prototype.all = Bluebird.coroutine(InternalEngineBootstrap.prototype._allGen);

InternalEngineBootstrap.prototype.getJWTSecret = Bluebird.coroutine(InternalEngineBootstrap.prototype._getJWTSecretGen);

InternalEngineBootstrap.prototype.lock = Bluebird.coroutine(InternalEngineBootstrap.prototype._lockGen);

module.exports = InternalEngineBootstrap;
<|endoftext|>


<commit_before>'use strict';

import mongoose from 'mongoose';
import chaiHttp from 'chai-http';
import sinon from 'sinon';
import chai from 'chai';

import {
  cardsModel,
  userModel
} from '../../../../src/models/index';

import prepareServer from '../../../../test/index';

chai.use(chaiHttp);

const boardsUrl = '/api/v1/boards/';
const loginUrl = '/api/v1/login/';

const assert   = chai.assert;

describe('Board' , () => {

  let boardStarId = '';
  let boardId = '';
  let cardId = '';

	let server;
	let stub;
	let app;

  before(done => {
    const userTest = new userModel({
      name: 'test',
			fullname: 'testFullname',
			email: 'test@email.com'
    });

		prepareServer(userTest, (arg1, arg2, arg3) => {
			server = arg1;
			stub = arg2;
			app = arg3;

			done();
		});
  });

	after(done => {
		cardsModel.find().remove().exec();
		userModel.find().remove().exec();
		stub.restore();

		server.close(done);
	});

	describe('/POST/board', () => {

		it ('should create a personal board - success', done => {
      const organization = {
				name: 'boardName',
			};

			chai.request(server)
				.post(boardsUrl)
        .send(organization)
				.end((err, res) => {
          boardId = res.body.data.boards[0]._id;

					assert.equal(res.status, '200', 'status equals 200')
					assert.equal(1, res.body.data.boards.length);
					assert.equal('boardName', res.body.data.boards[0].name);

					done();
				});
		});
	});

	describe('/POST/card', () => {

		it ('should create a board card - success', done => {
      const card = {
				name: 'cardName',
			};

			chai.request(server)
				.post(`${boardsUrl}/${boardId}/cards`)
        .send(card)
				.end((err, res) => {
          cardId = res.body.data.cards[0]._id;

					assert.equal(res.status, '200', 'status equals 200');
					assert.equal('cardName', res.body.data.cards[0].header);
					assert.equal(0, res.body.data.cards[0].cardItems.length);

					done();
				});
		});
	});

	describe('/POST/carditem', () => {

		it ('should create a board card item - success', done => {
      const cardItem = {
				name: 'cardItem',
			};

			chai.request(server)
				.post(`${boardsUrl}/${boardId}/cards/${cardId}`)
        .send(cardItem)
				.end((err, res) => {
					assert.equal(res.status, '200', 'status equals 200');
					assert.equal(1, res.body.data.cards[0].cardItems.length);
					assert.equal('cardItem', res.body.data.cards[0].cardItems[0].name);

					done();
				});
		});
	});

	describe('/POST/boardstars', () => {

		it ('should star a user board - success', done => {
			chai.request(server)
				.post(`${boardsUrl}/${boardId}/boardstars`)
				.end((err, res) => {
					boardStarId = res.body.data.boardStars[0]._id;

					assert.equal(res.status, '200', 'status equals 200')
					assert.equal(1, res.body.data.boardStars.length);
					assert.equal('boardName', res.body.data.boardStars[0].name);
					assert.equal(true, res.body.data.boardStars[0].isStarredBoard);

					done();
				});
		});

		it ('should star a user board - fail', done => {
			chai.request(server)
				.post(`${boardsUrl}/null/boardStars`)
				.end((err, res) => {
					assert.equal(res.status, '400',
							'status equals 400 because board id is not valid');

					done();
				});
		});
	});

	describe('/PUT/card', () => {

		it ('should create a board card - fail', done => {
			chai.request(server)
				.put(`${boardsUrl}/${boardId}`)
				.end((err, res) => {
					assert.equal(res.status, '400', 'status equals 400 because new card is missing');

					done();
				});
		});
	});

	describe('/GET/card', () => {

		it ('should get user board cards - success', done => {
			chai.request(server)
				.get(`${boardsUrl}/${boardId}/cards`)
				.end((err, res) => {
					assert.equal(res.status, '200');

					done();
				});
		});

		it ('should get user board cards - fail', done => {
			chai.request(server)
				.get(`${boardsUrl}/null`)
				.end((err, res) => {
					assert.equal(res.status, '404',
							'status equals 400 because board id is not valid');

					done();
				});
		});
	});

	describe('/PUT/board', () => {

		it ('should rename a personal board name - success', done => {
      const renamedBoardName = {
				name: 'renamedBoardName',
			};

			chai.request(server)
				.put(`${boardsUrl}/${boardId}`)
        .send(renamedBoardName)
				.end((err, res) => {
					assert.equal(res.status, '200', 'status equals 200');

					done();
				});
		});
	});

	describe('/DELETE/boardstars', () => {

		it ('should unstar a starred user board - success', done => {
			chai.request(server)
				.delete(`${boardsUrl}/${boardId}/boardstars`)
				.end((err, res) => {
					assert.equal(res.status, '200', 'status equals 200')
					assert.equal(0, res.body.data.boardStars.length);

					done();
				});
		});

		it ('should star a user board - fail', done => {
			chai.request(server)
				.post(`${boardsUrl}/null/boardStars`)
				.end((err, res) => {
					assert.equal(res.status, '400',
							'status equals 400 because board id is not valid');

					done();
				});
		});
	});

	describe('/DELETE/board', () => {

		it ('should delete a user board - success', done => {
			chai.request(server)
				.delete(`${boardsUrl}/${boardId}`)
				.end((err, res) => {
					assert.equal(res.status, '200', 'status equals 200')
					assert.equal(0, res.body.data.boards.length);

					done();
				});
		});
	});

	describe('fail', () => {
		assert.equal(1, 2)
	})
});<commit_msg>Fix board unit test<commit_after>'use strict';

import mongoose from 'mongoose';
import chaiHttp from 'chai-http';
import sinon from 'sinon';
import chai from 'chai';

import {
  cardsModel,
  userModel
} from '../../../../src/models/index';

import prepareServer from '../../../../test/index';

chai.use(chaiHttp);

const boardsUrl = '/api/v1/boards/';
const loginUrl = '/api/v1/login/';

const assert   = chai.assert;

describe('Board' , () => {

  let boardStarId = '';
  let boardId = '';
  let cardId = '';

	let server;
	let stub;
	let app;

  before(done => {
    const userTest = new userModel({
      name: 'test',
			fullname: 'testFullname',
			email: 'test@email.com'
    });

		prepareServer(userTest, (arg1, arg2, arg3) => {
			server = arg1;
			stub = arg2;
			app = arg3;

			done();
		});
  });

	after(done => {
		cardsModel.find().remove().exec();
		userModel.find().remove().exec();
		stub.restore();

		server.close(done);
	});

	describe('/POST/board', () => {

		it ('should create a personal board - success', done => {
      const organization = {
				name: 'boardName',
			};

			chai.request(server)
				.post(boardsUrl)
        .send(organization)
				.end((err, res) => {
          boardId = res.body.data.boards[0]._id;

					assert.equal(res.status, '200', 'status equals 200')
					assert.equal(1, res.body.data.boards.length);
					assert.equal('boardName', res.body.data.boards[0].name);

					done();
				});
		});
	});

	describe('/POST/card', () => {

		it ('should create a board card - success', done => {
      const card = {
				name: 'cardName',
			};

			chai.request(server)
				.post(`${boardsUrl}/${boardId}/cards`)
        .send(card)
				.end((err, res) => {
          cardId = res.body.data.cards[0]._id;

					assert.equal(res.status, '200', 'status equals 200');
					assert.equal('cardName', res.body.data.cards[0].header);
					assert.equal(0, res.body.data.cards[0].cardItems.length);

					done();
				});
		});
	});

	describe('/POST/carditem', () => {

		it ('should create a board card item - success', done => {
      const cardItem = {
				name: 'cardItem',
			};

			chai.request(server)
				.post(`${boardsUrl}/${boardId}/cards/${cardId}`)
        .send(cardItem)
				.end((err, res) => {
					assert.equal(res.status, '200', 'status equals 200');
					assert.equal(1, res.body.data.cards[0].cardItems.length);
					assert.equal('cardItem', res.body.data.cards[0].cardItems[0].name);

					done();
				});
		});
	});

	describe('/POST/boardstars', () => {

		it ('should star a user board - success', done => {
			chai.request(server)
				.post(`${boardsUrl}/${boardId}/boardstars`)
				.end((err, res) => {
					boardStarId = res.body.data.boardStars[0]._id;

					assert.equal(res.status, '200', 'status equals 200')
					assert.equal(1, res.body.data.boardStars.length);
					assert.equal('boardName', res.body.data.boardStars[0].name);
					assert.equal(true, res.body.data.boardStars[0].isStarredBoard);

					done();
				});
		});

		it ('should star a user board - fail', done => {
			chai.request(server)
				.post(`${boardsUrl}/null/boardStars`)
				.end((err, res) => {
					assert.equal(res.status, '400',
							'status equals 400 because board id is not valid');

					done();
				});
		});
	});

	describe('/PUT/card', () => {

		it ('should create a board card - fail', done => {
			chai.request(server)
				.put(`${boardsUrl}/${boardId}`)
				.end((err, res) => {
					assert.equal(res.status, '400', 'status equals 400 because new card is missing');

					done();
				});
		});
	});

	describe('/GET/card', () => {

		it ('should get user board cards - success', done => {
			chai.request(server)
				.get(`${boardsUrl}/${boardId}/cards`)
				.end((err, res) => {
					assert.equal(res.status, '200');

					done();
				});
		});

		it ('should get user board cards - fail', done => {
			chai.request(server)
				.get(`${boardsUrl}/null`)
				.end((err, res) => {
					assert.equal(res.status, '404',
							'status equals 400 because board id is not valid');

					done();
				});
		});
	});

	describe('/PUT/board', () => {

		it ('should rename a personal board name - success', done => {
      const renamedBoardName = {
				name: 'renamedBoardName',
			};

			chai.request(server)
				.put(`${boardsUrl}/${boardId}`)
        .send(renamedBoardName)
				.end((err, res) => {
					assert.equal(res.status, '200', 'status equals 200');

					done();
				});
		});
	});

	describe('/DELETE/boardstars', () => {

		it ('should unstar a starred user board - success', done => {
			chai.request(server)
				.delete(`${boardsUrl}/${boardId}/boardstars`)
				.end((err, res) => {
					assert.equal(res.status, '200', 'status equals 200')
					assert.equal(0, res.body.data.boardStars.length);

					done();
				});
		});

		it ('should star a user board - fail', done => {
			chai.request(server)
				.post(`${boardsUrl}/null/boardStars`)
				.end((err, res) => {
					assert.equal(res.status, '400',
							'status equals 400 because board id is not valid');

					done();
				});
		});
	});

	describe('/DELETE/board', () => {

		it ('should delete a user board - success', done => {
			chai.request(server)
				.delete(`${boardsUrl}/${boardId}`)
				.end((err, res) => {
					assert.equal(res.status, '200', 'status equals 200')
					assert.equal(0, res.body.data.boards.length);

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


<commit_before>/**
 * This file is part of the DreamFactory Services Platform(tm) (DSP)
 *
 * DreamFactory Services Platform(tm) <http://github.com/dreamfactorysoftware/dsp-core>
 * Copyright 2012-2014 DreamFactory Software, Inc. <support@dreamfactory.com>
 *
 * 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.
 */
var SchemaCtrl = function( dfLoadingScreen, $scope, DSP_URL, DB, $http, getSchemaServices ) {

    dfLoadingScreen.stop();

    Scope = $scope;
    $scope.typeOptions = [
        {value: "id"},
        {value: "string"},
        {value: "integer"},
        {value: "text"},
        {value: "boolean"},
        {value: "binary"},
        {value: "float"},
        {value: "decimal"},
        {value: "datetime"},
        {value: "date"},
        {value: "time"},
        {value: "reference"},
        {value: "user_id"},
        {value: "user_id_on_create"},
        {value: "user_id_on_update"},
        {value: "timestamp"},
        {value: "timestamp_on_create"},
        {value: "timestamp_on_update"}
    ];
    var editor;
    $scope.table = {};
    //$scope.service = {;
    $scope.advanced = false;
    //var service;
    editor = ace.edit("schema-editor");
    editor.getSession().setMode("ace/mode/json");
    $scope.dbServices = getSchemaServices.data.record;
    //console.log($scope.dbServices);
    $scope.loadServices = function(current){
        $scope.currentTables = [];
        if(current){
            $http.get(DSP_URL + "/rest/" + $scope.service + "/_schema").then(function(response){
                //console.log( $scope.dbServices[$scope.service]);
                $scope.dbServices[$scope.service_index].tables = [];
                response.data.resource.forEach(function(table){
                    $scope.dbServices[$scope.service_index].tables.push(table);
                    $scope.currentTables.push(table.name);
                })
            });
        }else{
            $scope.dbServices.forEach(function(service, index){
                $http.get(DSP_URL + "/rest/" + service.api_name + "/_schema").then(function(response){

                    service.tables = [];

                    service.service_index = index;
                    response.data.resource.forEach(function(table){

                        service.tables.push(table);
                        $scope.currentTables.push(table.name);

                    })
                });
            })
        }

    }
    $scope.loadServices();
    $scope.referenceFields  = [];
    $scope.loadNewSchema = function(table){
        $scope.import = false;
        $scope.table = table;
        $http.get(CurrentServer + "/rest/" + $scope.service + "/_schema/" + $scope.table.name)
            .then(function(response){
                $scope.table.schema = response;
            })
    }
    $scope.loadSchema = function(advanced){
        $scope.import = false;
        $scope.table = this.table;
        $scope.currentTable = $scope.table.name;
        $scope.service = this.service.api_name;
        $scope.service_index = this.service.service_index;
        $http.get(CurrentServer + "/rest/" + this.service.api_name + "/_schema/" + this.table.name)
            .then(function(response){
                $scope.table.schema = response;
                //console.log(table.schema);
                if(advanced){
                    $scope.advanced = true;
                    editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
                }else{
                    $scope.advanced = false;
                }

            })
    }
    $scope.loadReferenceFields = function(){
        var refTable = this.column.ref_table;
        $http.get(CurrentServer + "/rest/" + $scope.service + "/_schema/" + refTable)
            .then(function(response){
                //console.log(response);
                $scope.referenceFields = response.data.field;

            })
    }
    $scope.showImport = function(){
        editor.setValue("");
        $scope.advanced = true;
        $scope.import = true;
    }
    $scope.toggleJSON = function(){
        if($scope.advanced){
            $scope.table.schema.data = JSON.parse(editor.getValue());
            $scope.advanced = false;
        }else{
            $scope.advanced = true;
            editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
        }
    }
    $scope.addColumn = function(){
        $scope.newColumn = {
            name : "New_Column",
            is_new : true
        };
        //$scope.currentField = "New_Column";
        $scope.table.schema.data.field.unshift($scope.newColumn)
    }
    $scope.deleteColumn = function(){
        //console.log(this);
        if ( !confirm( "Are you sure you want to delete " + this.column.name) ) {
            return;
        }
        $scope.table.schema.data.field.splice(this.$index, 1);
        $(function(){
            new PNotify({
                title: 'Schema',
                text: 'Column removed from working set, press Update Schema to save changes',
                type: 'warning'
            });
        });

    }
    $scope.updateJSONSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true" , editor.getValue()).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.updateSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true" , {table:$scope.table.schema.data}).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.postJSONSchema = function(){
        $http.post(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true", editor.getValue()).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Posted Successfully',
                    type: 'success'
                });
            });
            $scope.loadServices(true);

        })
    }
    $scope.createTable = function(){
        var name = this.newTableName;
        this.newTableName = "";
        var requestObject = {
            name : name,
            field: [
                {name : "id",
                    type : "id"
                }
            ]
        };
        $http.post(CurrentServer + "/rest/" + this.service.api_name + "/_schema?return_schema=true" , {table:requestObject}).then(function(response){
            //$scope.loadServices();
            $scope.currentTable = name;
            $scope.currentTables.unshift(name);
            $scope.dbServices[$scope.service_index].tables.unshift(requestObject);
            $scope.loadNewSchema(requestObject);

        })
    }

    $scope.dropTable = function(){
        var table_index = this.$index;
        if ( !confirm( "Are you sure you want to delete " + this.table.name) ) {
            return;
        }
        $http.delete(CurrentServer + "/rest/" + this.service.api_name + "/_schema/" + this.table.name)
            .then(function(response){
                $scope.dbServices[$scope.service_index].tables.splice(table_index , 1);
                $scope.table = {};
            })
    }
    $scope.setService = function(){
        $scope.service = this.service.api_name;
        $scope.service_index = this.service.service_index;
    }
    $scope.validateJSON = function() {
        try {
            var result = JSON.parse( editor.getValue() );
            if ( result ) {
                $(function(){
                    new PNotify({
                        title: 'Schema',
                        text: 'JSON is valid',
                        type: 'success'
                    });
                });
                editor.setValue(angular.toJson(result, true), -1);
            }
        }
        catch ( e ) {
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: e,
                    type: 'error'
                });
            });
        }
    };
};

<commit_msg>moving service index from scope to elem<commit_after>/**
 * This file is part of the DreamFactory Services Platform(tm) (DSP)
 *
 * DreamFactory Services Platform(tm) <http://github.com/dreamfactorysoftware/dsp-core>
 * Copyright 2012-2014 DreamFactory Software, Inc. <support@dreamfactory.com>
 *
 * 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.
 */
var SchemaCtrl = function( dfLoadingScreen, $scope, DSP_URL, DB, $http, getSchemaServices ) {

    dfLoadingScreen.stop();

    Scope = $scope;
    $scope.typeOptions = [
        {value: "id"},
        {value: "string"},
        {value: "integer"},
        {value: "text"},
        {value: "boolean"},
        {value: "binary"},
        {value: "float"},
        {value: "decimal"},
        {value: "datetime"},
        {value: "date"},
        {value: "time"},
        {value: "reference"},
        {value: "user_id"},
        {value: "user_id_on_create"},
        {value: "user_id_on_update"},
        {value: "timestamp"},
        {value: "timestamp_on_create"},
        {value: "timestamp_on_update"}
    ];
    var editor;
    $scope.table = {};
    //$scope.service = {;
    $scope.advanced = false;
    //var service;
    editor = ace.edit("schema-editor");
    editor.getSession().setMode("ace/mode/json");
    $scope.dbServices = getSchemaServices.data.record;
    //console.log($scope.dbServices);
    $scope.loadServices = function(current){
        $scope.currentTables = [];
        if(current){
            $http.get(DSP_URL + "/rest/" + $scope.service + "/_schema").then(function(response){
                //console.log( $scope.dbServices[$scope.service]);
                $scope.dbServices[$scope.service_index].tables = [];
                response.data.resource.forEach(function(table){
                    $scope.dbServices[$scope.service_index].tables.push(table);
                    $scope.currentTables.push(table.name);
                })
            });
        }else{
            $scope.dbServices.forEach(function(service, index){
                $http.get(DSP_URL + "/rest/" + service.api_name + "/_schema").then(function(response){

                    service.tables = [];

                    service.service_index = index;
                    response.data.resource.forEach(function(table){

                        service.tables.push(table);
                        $scope.currentTables.push(table.name);

                    })
                });
            })
        }

    }
    $scope.loadServices();
    $scope.referenceFields  = [];
    $scope.loadNewSchema = function(table){
        $scope.import = false;
        $scope.table = table;
        $http.get(CurrentServer + "/rest/" + $scope.service + "/_schema/" + $scope.table.name)
            .then(function(response){
                $scope.table.schema = response;
            })
    }
    $scope.loadSchema = function(advanced){
        $scope.import = false;
        $scope.table = this.table;
        $scope.currentTable = $scope.table.name;
        $scope.service = this.service.api_name;
        $scope.service_index = this.service.service_index;
        $http.get(CurrentServer + "/rest/" + this.service.api_name + "/_schema/" + this.table.name)
            .then(function(response){
                $scope.table.schema = response;
                //console.log(table.schema);
                if(advanced){
                    $scope.advanced = true;
                    editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
                }else{
                    $scope.advanced = false;
                }

            })
    }
    $scope.loadReferenceFields = function(){
        var refTable = this.column.ref_table;
        $http.get(CurrentServer + "/rest/" + $scope.service + "/_schema/" + refTable)
            .then(function(response){
                //console.log(response);
                $scope.referenceFields = response.data.field;

            })
    }
    $scope.showImport = function(){
        editor.setValue("");
        $scope.advanced = true;
        $scope.import = true;
    }
    $scope.toggleJSON = function(){
        if($scope.advanced){
            $scope.table.schema.data = JSON.parse(editor.getValue());
            $scope.advanced = false;
        }else{
            $scope.advanced = true;
            editor.setValue(angular.toJson($scope.table.schema.data, true), -1);
        }
    }
    $scope.addColumn = function(){
        $scope.newColumn = {
            name : "New_Column",
            is_new : true
        };
        //$scope.currentField = "New_Column";
        $scope.table.schema.data.field.unshift($scope.newColumn)
    }
    $scope.deleteColumn = function(){
        //console.log(this);
        if ( !confirm( "Are you sure you want to delete " + this.column.name) ) {
            return;
        }
        $scope.table.schema.data.field.splice(this.$index, 1);
        $(function(){
            new PNotify({
                title: 'Schema',
                text: 'Column removed from working set, press Update Schema to save changes',
                type: 'warning'
            });
        });

    }
    $scope.updateJSONSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true" , editor.getValue()).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.updateSchema = function(){
        $http.put(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true" , {table:$scope.table.schema.data}).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Updated Successfully',
                    type: 'success'
                });
            });
        })
    }
    $scope.postJSONSchema = function(){
        $http.post(CurrentServer + "/rest/" + $scope.service + "/_schema?return_schema=true", editor.getValue()).then(function(response){
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: 'Posted Successfully',
                    type: 'success'
                });
            });
            $scope.loadServices(true);

        })
    }
    $scope.createTable = function(){
        var name = this.newTableName;
        this.newTableName = "";
        var requestObject = {
            name : name,
            field: [
                {name : "id",
                    type : "id"
                }
            ]
        };
        $http.post(CurrentServer + "/rest/" + this.service.api_name + "/_schema?return_schema=true" , {table:requestObject}).then(function(response){
            //$scope.loadServices();
            $scope.currentTable = name;
            $scope.currentTables.unshift(name);
            $scope.dbServices[$scope.service_index].tables.unshift(requestObject);
            $scope.loadNewSchema(requestObject);

        })
    }

    $scope.dropTable = function(){
        var table_index = this.$index;
        var service_index = this.service.service_index;

        if ( !confirm( "Are you sure you want to delete " + this.table.name) ) {
            return;
        }
        $http.delete(CurrentServer + "/rest/" + this.service.api_name + "/_schema/" + this.table.name)
            .then(function(){
                $scope.dbServices[service_index].tables.splice(table_index , 1);
                $scope.table = {};
            })
    }
    $scope.setService = function(){
        $scope.service = this.service.api_name;
        $scope.service_index = this.service.service_index;
    }
    $scope.validateJSON = function() {
        try {
            var result = JSON.parse( editor.getValue() );
            if ( result ) {
                $(function(){
                    new PNotify({
                        title: 'Schema',
                        text: 'JSON is valid',
                        type: 'success'
                    });
                });
                editor.setValue(angular.toJson(result, true), -1);
            }
        }
        catch ( e ) {
            $(function(){
                new PNotify({
                    title: 'Schema',
                    text: e,
                    type: 'error'
                });
            });
        }
    };
};

<|endoftext|>