<commit_before>import PropTypes from "prop-types";
import React, { useContext, useEffect, useMemo } from "react";
import { StateInspector, useReducer } from "reinspect";
import { ThemeProvider } from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import rootReducer from "@agir/front/globalContext/reducers";
import createDispatch, {
  initFromScriptTag,
  setSessionContext,
} from "@agir/front/globalContext/actions";
import Toasts from "@agir/front/globalContext/Toast";
import useSWR from "swr";

import logger from "@agir/lib/utils/logger";
const log = logger(__filename);

const GlobalContext = React.createContext({});

const ProdProvider = ({ hasToasts = false, children }) => {
  const [state, dispatch] = useReducer(
    rootReducer,
    rootReducer({}, initFromScriptTag()),
    (state) => state,
    "GC"
  );

  const doDispatch = useMemo(() => createDispatch(dispatch), [dispatch]);

  const { data: sessionContext } = useSWR("/api/session/");

  useEffect(() => {
    if (!sessionContext) return;

    if (!sessionContext.user) {
      self.caches.delete("session");
    }

    doDispatch(setSessionContext(sessionContext));
    log.debug("Update session context", sessionContext);
  }, [doDispatch, sessionContext]);

  return (
    <GlobalContext.Provider value={{ state, dispatch: doDispatch }}>
      <ThemeProvider theme={style}>
        {children}
        {hasToasts ? <Toasts /> : null}
      </ThemeProvider>
    </GlobalContext.Provider>
  );
};
const DevProvider = (props) => {
  return (
    <StateInspector name="actionpopulaire">
      <ProdProvider {...props} />
    </StateInspector>
  );
};
DevProvider.propTypes = ProdProvider.propTypes = {
  children: PropTypes.element,
  hasToasts: PropTypes.bool,
};

export const GlobalContextProvider =
  process.env.NODE_ENV === "production" ? ProdProvider : DevProvider;

export const TestGlobalContextProvider = ({ children, value }) => {
  const [state] = useReducer(rootReducer, rootReducer({}, initFromScriptTag()));
  const doDispatch = useMemo(() => () => {}, []);
  const currentState = useMemo(
    () => ({
      state: {
        ...state,
        ...value,
      },
      dispatch: doDispatch,
    }),
    [state, value, doDispatch]
  );

  return (
    <GlobalContext.Provider value={currentState}>
      {children}
    </GlobalContext.Provider>
  );
};
TestGlobalContextProvider.propTypes = {
  children: PropTypes.node,
  value: PropTypes.object,
};

export const useGlobalContext = () => useContext(GlobalContext);
export const useSelector = (selector) => {
  const { state } = useContext(GlobalContext);
  return selector(state);
};
export const useDispatch = () => {
  const { dispatch } = useContext(GlobalContext);
  return dispatch;
};
<commit_msg>fix: do not try to access caches in insecure contexts<commit_after>import PropTypes from "prop-types";
import React, { useContext, useEffect, useMemo } from "react";
import { StateInspector, useReducer } from "reinspect";
import { ThemeProvider } from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import rootReducer from "@agir/front/globalContext/reducers";
import createDispatch, {
  initFromScriptTag,
  setSessionContext,
} from "@agir/front/globalContext/actions";
import Toasts from "@agir/front/globalContext/Toast";
import useSWR from "swr";

import logger from "@agir/lib/utils/logger";
const log = logger(__filename);

const GlobalContext = React.createContext({});

const ProdProvider = ({ hasToasts = false, children }) => {
  const [state, dispatch] = useReducer(
    rootReducer,
    rootReducer({}, initFromScriptTag()),
    (state) => state,
    "GC"
  );

  const doDispatch = useMemo(() => createDispatch(dispatch), [dispatch]);

  const { data: sessionContext } = useSWR("/api/session/");

  useEffect(() => {
    if (!sessionContext) return;

    if (!sessionContext.user) {
      if (self.isSecureContext) {
        self.caches.delete("session");
      }
    }

    doDispatch(setSessionContext(sessionContext));
    log.debug("Update session context", sessionContext);
  }, [doDispatch, sessionContext]);

  return (
    <GlobalContext.Provider value={{ state, dispatch: doDispatch }}>
      <ThemeProvider theme={style}>
        {children}
        {hasToasts ? <Toasts /> : null}
      </ThemeProvider>
    </GlobalContext.Provider>
  );
};
const DevProvider = (props) => {
  return (
    <StateInspector name="actionpopulaire">
      <ProdProvider {...props} />
    </StateInspector>
  );
};
DevProvider.propTypes = ProdProvider.propTypes = {
  children: PropTypes.element,
  hasToasts: PropTypes.bool,
};

export const GlobalContextProvider =
  process.env.NODE_ENV === "production" ? ProdProvider : DevProvider;

export const TestGlobalContextProvider = ({ children, value }) => {
  const [state] = useReducer(rootReducer, rootReducer({}, initFromScriptTag()));
  const doDispatch = useMemo(() => () => {}, []);
  const currentState = useMemo(
    () => ({
      state: {
        ...state,
        ...value,
      },
      dispatch: doDispatch,
    }),
    [state, value, doDispatch]
  );

  return (
    <GlobalContext.Provider value={currentState}>
      {children}
    </GlobalContext.Provider>
  );
};
TestGlobalContextProvider.propTypes = {
  children: PropTypes.node,
  value: PropTypes.object,
};

export const useGlobalContext = () => useContext(GlobalContext);
export const useSelector = (selector) => {
  const { state } = useContext(GlobalContext);
  return selector(state);
};
export const useDispatch = () => {
  const { dispatch } = useContext(GlobalContext);
  return dispatch;
};
<|endoftext|>


<commit_before>app.controller(DIALOG_SEGMENT, function($scope, ui)
{
	$scope.form = {
		id: '',
		key: '',
		translations: {},
		description: '',
		tags: '',
		maxLength: '',
		screenshot: '',
		isPlural: false,
		isArray: false
	}

	$scope.openAdd = function(languages)
	{
		$scope.form.id          = ''
		$scope.form.key         = ''
		$scope.form.description = ''
		$scope.form.tags        = ''
		$scope.form.maxLength   = ''
		$scope.form.screenshot  = ''
		$scope.form.isPlural    = false
		$scope.form.isArray     = false

		for (const index in languages)
		{
			$scope.form.translations[index] = {
				value: '',
				validated: false
			}
		}

		open()
	}

	$scope.openEdit = function(languages, segment)
	{
		$scope.form.id          = segment.id
		$scope.form.key         = segment.key
		$scope.form.description = segment.description
		$scope.form.tags        = segment.tags
		$scope.form.maxLength   = segment.maxLength
		$scope.form.screenshot  = segment.screenshot
		$scope.form.isPlural    = segment.isPlural
		$scope.form.isArray     = segment.isArray

		for (const index in languages)
		{
			$scope.form.translations[index] = {
				value: segment.translations[index].value,
				validated: segment.translations[index].validated,
				history: segment.translations[index].history,
			}
		}

		open()
	}

	$scope.historyEmpty = function(history)
	{
		return !history || (Object.keys(history).length == 0)
	}

	function open()
	{
		ui.dialog(DIALOG_SEGMENT).on('shown.bs.modal', function()
		{
			ui.focus('dialog-segment-key')
		})

		ui.openTab('dialog-segment-tabs', 'first')

		ui.openDialog(DIALOG_SEGMENT)
	}

	$scope.onAddSegment = function(form)
	{
		controller(CONTROLLER_SEGMENTS).addSegment(form)

		ui.closeDialog(DIALOG_SEGMENT)
	}

	$scope.onEditSegment = function(form)
	{
		controller(CONTROLLER_SEGMENTS).editSegment(form)

		ui.closeDialog(DIALOG_SEGMENT)
	}

	$scope.openSegmentHistory = function(history)
	{
		controller(DIALOG_TRANSLATION_HISTORY).open(history)
	}

	$scope.openSegmentComments = function(languageId, comments)
	{
		controller(DIALOG_TRANSLATION_COMMENTS).open($scope.form.id, languageId, comments)
	}
})<commit_msg>Fixed bug displaying comments<commit_after>app.controller(DIALOG_SEGMENT, function($scope, ui)
{
	$scope.form = {
		id: '',
		key: '',
		translations: {},
		description: '',
		tags: '',
		maxLength: '',
		screenshot: '',
		isPlural: false,
		isArray: false
	}

	$scope.openAdd = function(languages)
	{
		$scope.form.id          = ''
		$scope.form.key         = ''
		$scope.form.description = ''
		$scope.form.tags        = ''
		$scope.form.maxLength   = ''
		$scope.form.screenshot  = ''
		$scope.form.isPlural    = false
		$scope.form.isArray     = false

		for (const index in languages)
		{
			$scope.form.translations[index] = {
				value: '',
				validated: false
			}
		}

		open()
	}

	$scope.openEdit = function(languages, segment)
	{
		$scope.form.id          = segment.id
		$scope.form.key         = segment.key
		$scope.form.description = segment.description
		$scope.form.tags        = segment.tags
		$scope.form.maxLength   = segment.maxLength
		$scope.form.screenshot  = segment.screenshot
		$scope.form.isPlural    = segment.isPlural
		$scope.form.isArray     = segment.isArray

		for (const index in languages)
		{
			$scope.form.translations[index] = {
				value: segment.translations[index].value,
				validated: segment.translations[index].validated,
				history: segment.translations[index].history,
				comments: segment.translations[index].comments
			}
		}

		open()
	}

	$scope.historyEmpty = function(history)
	{
		return !history || (Object.keys(history).length == 0)
	}

	function open()
	{
		ui.dialog(DIALOG_SEGMENT).on('shown.bs.modal', function()
		{
			ui.focus('dialog-segment-key')
		})

		ui.openTab('dialog-segment-tabs', 'first')

		ui.openDialog(DIALOG_SEGMENT)
	}

	$scope.onAddSegment = function(form)
	{
		controller(CONTROLLER_SEGMENTS).addSegment(form)

		ui.closeDialog(DIALOG_SEGMENT)
	}

	$scope.onEditSegment = function(form)
	{
		controller(CONTROLLER_SEGMENTS).editSegment(form)

		ui.closeDialog(DIALOG_SEGMENT)
	}

	$scope.openSegmentHistory = function(history)
	{
		controller(DIALOG_TRANSLATION_HISTORY).open(history)
	}

	$scope.openSegmentComments = function(languageId, comments)
	{
		controller(DIALOG_TRANSLATION_COMMENTS).open($scope.form.id, languageId, comments)
	}
})<|endoftext|>


<commit_before>var element = document.getElementsByTagName("body")[0].children[0]

element.innerHTML = "Hej du"
var pokemons = []
var moves = []

function update(){
    var pokesA = moves["False Swipe"].pokemons
    var pokesB = moves["Spore"].pokemons
    var pokes = []
    for(var i in pokesA){
        for(var j in pokesB){
            if(pokesA[i].id == pokesB[j].id && pokesA[i].form == pokesB[j].form)
            pokes.push(pokesA[i])
        }
    }
    var result = ""
    for(var i in pokes){
        result += JSON.stringify(pokes[i]) + ",
"
    }
    element.innerHTML = result
}

function request(url, callback) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText)
    }
    xmlHttp.open("GET", url, true)
    xmlHttp.send()
}

function getMoves(response){
    moves = JSON.parse(response)
    if(moves && pokemons)
        update()
}

function getPokemons(response){
    pokemons = JSON.parse(response)
    if(moves && pokemons)
        update()
}

request("https://armienn.github.io/pokemon/static/moves.json", getMoves);
request("https://armienn.github.io/pokemon/static/pokemons-small.json", getPokemons);<commit_msg>Added filter functions<commit_after>var element = document.getElementsByTagName("body")[0].children[0]

element.innerHTML = "Hej du"
var pokemons = []
var moves = []

function update(){
	var pokes = pokemons.filter(hasMoveAmongFilter("tackle"))
	pokes = pokes.filter(hasAbilityAmongFilter("intimidate"))
	var result = ""
	for(var i in pokes){
		result += (pokes[i].form == "Base" ? "" : pokes[i].form + " " ) + pokes[i].name + "
"
		//result += JSON.stringify(pokes[i]) + "
"
	}
	element.innerHTML = result
}

function hasMoveAmongFilter(...moves) {
	return function(pokemon) {
		for(var i in moves){
			if(pokemon.moves.filter(e => e.name.toLowerCase() == moves[i].toLowerCase()).length)
				return true
		}
		return false
	}
}

function hasAbilityAmongFilter(...abilities) {
	return function(pokemon) {
		for(var i in abilities){
			if(pokemon.abilities.filter(e => e ? e.toLowerCase() == abilities[i].toLowerCase() : false).length)
				return true
		}
		return false
	}
}

function request(url, callback) {
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
			callback(xmlHttp.responseText)
	}
	xmlHttp.open("GET", url, true)
	xmlHttp.send()
}

function getMoves(response){
	moves = JSON.parse(response)
	if(moves && pokemons)
		update()
}

function getPokemons(response){
	pokemons = JSON.parse(response)
	if(moves && pokemons)
		update()
}

request("https://armienn.github.io/pokemon/static/moves.json", getMoves);
request("https://armienn.github.io/pokemon/static/pokemons-small.json", getPokemons);<|endoftext|>


<commit_before>var fs = require("fs");

// Browsers to run on Sauce Labs
var customLaunchers = {
    sl_chrome: {
        base: "SauceLabs",
        browserName: "chrome",
        platform: "Windows 7",
        version: "47"
    },
    sl_firefox: {
        base: "SauceLabs",
        browserName: "firefox",
        platform: "Windows 7",
        version: "43"
    },
    el_opera_12: {
        base: "SauceLabs",
        browserName: "opera",
        platform: "Windows 7",
        version: "12"
    },
    sl_safari: {
        base: "SauceLabs",
        browserName: "safari",
        platform: "OS X 10.11",
        version: "9",
        deviceName: ""
    },
    sl_ie_11: {
        base: "SauceLabs",
        browserName: "internet explorer",
        platform: "Windows 7",
        version: "11"
    },
    // sl_ie_10: {
    //     base: "SauceLabs",
    //     browserName: "internet explorer",
    //     platform: "Windows 7",
    //     version: "10"
    // },
    // sl_ie_8: {
    //     base: "SauceLabs",
    //     browserName: "internet explorer",
    //     platform: "Windows XP",
    //     version: "8"
    // },
    // sl_ie_9: {
    //     base: "SauceLabs",
    //     browserName: "internet explorer",
    //     platform: "Windows 7",
    //     version: "9"
    // },
    sl_ios_safari_9: {
        base: "SauceLabs",
        browserName: "iphone",
        platform: "OS X 10.11",
        version: "9.2"
    },
    sl_android_5_1: {
        base: "SauceLabs",
        browserName: "android",
        platform: "Linux",
        version: "5.1"
    },
};

module.exports = function(config) {
    // Use ENV vars on Travis and sauce.json locally to get credentials
    if (!process.env.SAUCE_USERNAME) {
        if (!fs.existsSync("sauce.json")) {
            console.log("Create a sauce.json with your credentials based on the https://github.com/saucelabs/karma-sauce-example/blob/master/sauce-sample.json file.");
            process.exit(1);
        } else {
            process.env.SAUCE_USERNAME = require("./sauce").username;
            process.env.SAUCE_ACCESS_KEY = require("./sauce").accessKey;
        }
    }

    config.set({
        basePath: "..",
        frameworks: ["jasmine"],
        singleRun: true,

        reporters: ["saucelabs"],

        colors: true,
        captureTimeout: 120000,
        logLevel: config.LOG_INFO,

        sauceLabs: {
            testName: "better-dom",
            startConnect: !process.env.TRAVIS_JOB_NUMBER,
            tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
        },

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: Object.keys(customLaunchers),
        customLaunchers: customLaunchers,

        files: [
            // legacy IE file includes
            {pattern: "./build/better-dom-legacy.htc", served: true, included: false},
            "./build/better-dom-legacy.js",
            // normal browser file includes
            "./test/lib/jasmine-better-dom-matchers.js",
            "./build/better-dom.js",
            "./test/spec/**/*.spec.js"
        ]
    });
};
<commit_msg>update saucelabs browsers<commit_after>var fs = require("fs");

// Browsers to run on Sauce Labs
var customLaunchers = {
    sl_chrome: {
        base: "SauceLabs",
        browserName: "chrome",
        platform: "Windows 10"
    },
    sl_firefox: {
        base: "SauceLabs",
        browserName: "firefox",
        platform: "Windows 10"
    },
    el_opera_12: {
        base: "SauceLabs",
        browserName: "opera",
        platform: "Windows 7",
        version: "12"
    },
    sl_safari: {
        base: "SauceLabs",
        browserName: "safari",
        platform: "OS X 10.11"
    },
    sl_ie_11: {
        base: "SauceLabs",
        browserName: "internet explorer",
        platform: "Windows 7",
        version: "11"
    },
    sl_edge_20: {
        base: "SauceLabs",
        browserName: "edge",
        platform: "Windows 10"
    },
    // sl_ie_10: {
    //     base: "SauceLabs",
    //     browserName: "internet explorer",
    //     platform: "Windows 7",
    //     version: "10"
    // },
    // sl_ie_8: {
    //     base: "SauceLabs",
    //     browserName: "internet explorer",
    //     platform: "Windows XP",
    //     version: "8"
    // },
    // sl_ie_9: {
    //     base: "SauceLabs",
    //     browserName: "internet explorer",
    //     platform: "Windows 7",
    //     version: "9"
    // },
    sl_ios_safari_9: {
        base: "SauceLabs",
        browserName: "iphone",
        platform: "OS X 10.11",
        version: "9.2"
    },
    sl_android_5_1: {
        base: "SauceLabs",
        browserName: "android",
        platform: "Linux",
        version: "5.1"
    },
};

module.exports = function(config) {
    // Use ENV vars on Travis and sauce.json locally to get credentials
    if (!process.env.SAUCE_USERNAME) {
        if (!fs.existsSync("sauce.json")) {
            console.log("Create a sauce.json with your credentials based on the https://github.com/saucelabs/karma-sauce-example/blob/master/sauce-sample.json file.");
            process.exit(1);
        } else {
            process.env.SAUCE_USERNAME = require("./sauce").username;
            process.env.SAUCE_ACCESS_KEY = require("./sauce").accessKey;
        }
    }

    config.set({
        basePath: "..",
        frameworks: ["jasmine"],
        singleRun: true,

        reporters: ["saucelabs"],

        colors: true,
        captureTimeout: 120000,
        logLevel: config.LOG_INFO,

        sauceLabs: {
            testName: "better-dom",
            startConnect: !process.env.TRAVIS_JOB_NUMBER,
            tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
        },

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: Object.keys(customLaunchers),
        customLaunchers: customLaunchers,

        files: [
            // legacy IE file includes
            {pattern: "./build/better-dom-legacy.htc", served: true, included: false},
            "./build/better-dom-legacy.js",
            // normal browser file includes
            "./test/lib/jasmine-better-dom-matchers.js",
            "./build/better-dom.js",
            "./test/spec/**/*.spec.js"
        ]
    });
};
<|endoftext|>


<commit_before>'use strict';

angularMoonApp.controller('HeaderController', ['$scope', function ($scope) {

}]);<commit_msg>Modified the header controller to set the current location<commit_after>'use strict';

angularMoonApp.controller('HeaderController', ['$scope', '$location', function ($scope, $location) {
  $scope.currentItem = 'home';
  switch($location.path()) {
    case '/':
      $scope.currentItem = 'home'
      break;
    case '/'
  }
}]);<|endoftext|>


<commit_before>DynamicsVisualizer.Materials = {};
DynamicsVisualizer.Geometries = ['Shape', 'Cube', 'Cylinder',
                                 'Cone', 'Sphere', 'Circle',
                                 'Plane', 'Tetrahedron',
                                 'Octahedron', 'Icosahedron',
                                 'Torus', 'TorusKnot', 'Tube',
                                 'Mesh'];
DynamicsVisualizer.Materials["default"] = new THREE.MeshLambertMaterial();
function loadMaterials() {

    var checkerBoardTexture = THREE.ImageUtils.loadTexture( "textures/checkerboard.jpg" );
    checkerBoardTexture.wrapS = checkerBoardTexture.wrapT = THREE.RepeatWrapping;
    checkerBoardTexture.anisotropy = 4;

    var metalTexture = THREE.ImageUtils.loadTexture( "textures/metal.jpg" );
    metalTexture.wrapS = metalTexture.wrapT = THREE.RepeatWrapping;
    metalTexture.repeat.set(2,2);
    metalTexture.anisotropy = 4;

    var moonTexture = THREE.ImageUtils.loadTexture( "textures/moon.jpg" );
    moonTexture.wrapS = moonTexture.wrapT = THREE.RepeatWrapping;
    moonTexture.anisotropy = 4;

    var earthTexture = THREE.ImageUtils.loadTexture( "textures/earth.jpg" );
    earthTexture.wrapS = earthTexture.wrapT = THREE.RepeatWrapping;
    earthTexture.anisotropy = 4;

    var grassTexture = THREE.ImageUtils.loadTexture( "textures/grass.jpg" );
    grassTexture.wrapS = grassTexture.wrapT = THREE.RepeatWrapping;
    grassTexture.repeat.set(1,1);
    grassTexture.anisotropy = 4;

    var dirtTexture = THREE.ImageUtils.loadTexture( "textures/dirt.jpg" );
    dirtTexture.wrapS = dirtTexture.wrapT = THREE.RepeatWrapping;
    dirtTexture.repeat.set(1,1);
    dirtTexture.anisotropy = 4;

    var waterTexture = THREE.ImageUtils.loadTexture( "textures/water.jpg" );
    waterTexture.wrapS = waterTexture.wrapT = THREE.RepeatWrapping;
    waterTexture.repeat.set(1,1);
    waterTexture.anisotropy = 4;

    var lavaTexture = THREE.ImageUtils.loadTexture( "textures/lavatile.jpg" );
    lavaTexture.repeat.set( 4, 2 );
    lavaTexture.wrapS = lavaTexture.wrapT = THREE.RepeatWrapping;
    lavaTexture.anisotropy = 4;

    var shininess = 50, specular = 0x333333, shading = THREE.SmoothShading;

    DynamicsVisualizer.Materials["checkerboard"] = new THREE.MeshPhongMaterial(
        {   map: checkerBoardTexture,
            bumpMap: null,
            bumpScale: 0,
            color: 0xffffff,
            ambient: 0x555555,
            specular: 0x222222,
            shininess: 10,
            shading: shading } );

    DynamicsVisualizer.Materials["metal"] = new THREE.MeshPhongMaterial(
        {   map: metalTexture,
            bumpMap: metalTexture,
            bumpScale: 0.1,
            color: 0xffffff,
            ambient: 0x555555,
            specular: 0x222222,
            shininess: 70,
            shading: shading } );

    DynamicsVisualizer.Materials["dirt"] = new THREE.MeshPhongMaterial(
        {   map: dirtTexture,
            bumpMap: dirtTexture,
            bumpScale: 0.05,
            color: 0xffffff,
            ambient: 0x555555,
            specular: 0x222222,
            shininess: 10,
            shading: shading } );

    DynamicsVisualizer.Materials["foil"] = new THREE.MeshPhongMaterial(
        {   map: waterTexture,
            bumpMap: waterTexture,
            bumpScale: 0.3,
            color: 0xccccaa,
            ambient: 0x555544,
            specular: 0x777777,
            shininess: 100,
            shading: shading } );

    DynamicsVisualizer.Materials["water"] = new THREE.MeshPhongMaterial(
        {   map: waterTexture,
            bumpMap: waterTexture,
            bumpScale: 0.05,
            color: 0x3333aa,
            ambient: 0x335577,
            specular: 0x555555,
            shininess: shininess,
            shading: shading } );

    DynamicsVisualizer.Materials["grass"] = new THREE.MeshPhongMaterial(
        {   map: grassTexture,
            bumpMap: grassTexture,
            bumpScale: 0.05,
            color: 0xffffff,
            ambient: 0x777777,
            specular: 0x333333,
            opacity: 1,
            shininess: shininess,
            shading: shading } );

    DynamicsVisualizer.Materials["lava"] = new THREE.MeshPhongMaterial(
        {   map: lavaTexture,
            bumpMap: lavaTexture,
            bumpScale: 0.5,
            color: 0xffffff,
            ambient: 0x777777,
            specular: 0x333333,
            shininess: shininess,
            shading: shading } );

    DynamicsVisualizer.Materials["moon"] = new THREE.MeshPhongMaterial(
        {   map: moonTexture,
            bumpMap: moonTexture,
            bumpScale: 0.0001,
            color: 0xffffff,
            ambient: 0x777777,
            specular: 0x333333,
            shininess: 0,
            shading: shading } );

    DynamicsVisualizer.Materials["earth"] = new THREE.MeshPhongMaterial(
        {   map: earthTexture,
            color: 0xffffff,
            ambient: 0x777777,
            specular: 0x333333,
            shininess: shininess,
            shading: shading } );

}
loadMaterials();
<commit_msg>Fixed texture loading<commit_after>DynamicsVisualizer.Materials = {};
DynamicsVisualizer.Geometries = ['Shape', 'Cube', 'Cylinder',
                                 'Cone', 'Sphere', 'Circle',
                                 'Plane', 'Tetrahedron',
                                 'Octahedron', 'Icosahedron',
                                 'Torus', 'TorusKnot', 'Tube',
                                 'Mesh'];
DynamicsVisualizer.Materials["default"] = new THREE.MeshLambertMaterial();
DynamicsVisualizer.texture_base_path = "static/textures/"

// If IPython,
if(typeof IPython == "undefined"){

    DynamicsVisualizer.texture_base_path = "textures/";

}

function loadMaterials() {

    var checkerBoardTexture = THREE.ImageUtils.loadTexture( DynamicsVisualizer.texture_base_path + "checkerboard.jpg" );
    checkerBoardTexture.wrapS = checkerBoardTexture.wrapT = THREE.RepeatWrapping;
    checkerBoardTexture.anisotropy = 4;

    var metalTexture = THREE.ImageUtils.loadTexture( DynamicsVisualizer.texture_base_path + "metal.jpg" );
    metalTexture.wrapS = metalTexture.wrapT = THREE.RepeatWrapping;
    metalTexture.repeat.set(2,2);
    metalTexture.anisotropy = 4;

    var moonTexture = THREE.ImageUtils.loadTexture( DynamicsVisualizer.texture_base_path + "moon.jpg" );
    moonTexture.wrapS = moonTexture.wrapT = THREE.RepeatWrapping;
    moonTexture.anisotropy = 4;

    var earthTexture = THREE.ImageUtils.loadTexture( DynamicsVisualizer.texture_base_path + "earth.jpg" );
    earthTexture.wrapS = earthTexture.wrapT = THREE.RepeatWrapping;
    earthTexture.anisotropy = 4;

    var grassTexture = THREE.ImageUtils.loadTexture( DynamicsVisualizer.texture_base_path + "grass.jpg" );
    grassTexture.wrapS = grassTexture.wrapT = THREE.RepeatWrapping;
    grassTexture.repeat.set(1,1);
    grassTexture.anisotropy = 4;

    var dirtTexture = THREE.ImageUtils.loadTexture( DynamicsVisualizer.texture_base_path + "dirt.jpg" );
    dirtTexture.wrapS = dirtTexture.wrapT = THREE.RepeatWrapping;
    dirtTexture.repeat.set(1,1);
    dirtTexture.anisotropy = 4;

    var waterTexture = THREE.ImageUtils.loadTexture( DynamicsVisualizer.texture_base_path + "water.jpg" );
    waterTexture.wrapS = waterTexture.wrapT = THREE.RepeatWrapping;
    waterTexture.repeat.set(1,1);
    waterTexture.anisotropy = 4;

    var lavaTexture = THREE.ImageUtils.loadTexture( DynamicsVisualizer.texture_base_path + "lavatile.jpg" );
    lavaTexture.repeat.set( 4, 2 );
    lavaTexture.wrapS = lavaTexture.wrapT = THREE.RepeatWrapping;
    lavaTexture.anisotropy = 4;

    var shininess = 50, specular = 0x333333, shading = THREE.SmoothShading;

    DynamicsVisualizer.Materials["checkerboard"] = new THREE.MeshPhongMaterial(
        {   map: checkerBoardTexture,
            bumpMap: null,
            bumpScale: 0,
            color: 0xffffff,
            ambient: 0x555555,
            specular: 0x222222,
            shininess: 10,
            shading: shading } );

    DynamicsVisualizer.Materials["metal"] = new THREE.MeshPhongMaterial(
        {   map: metalTexture,
            bumpMap: metalTexture,
            bumpScale: 0.1,
            color: 0xffffff,
            ambient: 0x555555,
            specular: 0x222222,
            shininess: 70,
            shading: shading } );

    DynamicsVisualizer.Materials["dirt"] = new THREE.MeshPhongMaterial(
        {   map: dirtTexture,
            bumpMap: dirtTexture,
            bumpScale: 0.05,
            color: 0xffffff,
            ambient: 0x555555,
            specular: 0x222222,
            shininess: 10,
            shading: shading } );

    DynamicsVisualizer.Materials["foil"] = new THREE.MeshPhongMaterial(
        {   map: waterTexture,
            bumpMap: waterTexture,
            bumpScale: 0.3,
            color: 0xccccaa,
            ambient: 0x555544,
            specular: 0x777777,
            shininess: 100,
            shading: shading } );

    DynamicsVisualizer.Materials["water"] = new THREE.MeshPhongMaterial(
        {   map: waterTexture,
            bumpMap: waterTexture,
            bumpScale: 0.05,
            color: 0x3333aa,
            ambient: 0x335577,
            specular: 0x555555,
            shininess: shininess,
            shading: shading } );

    DynamicsVisualizer.Materials["grass"] = new THREE.MeshPhongMaterial(
        {   map: grassTexture,
            bumpMap: grassTexture,
            bumpScale: 0.05,
            color: 0xffffff,
            ambient: 0x777777,
            specular: 0x333333,
            opacity: 1,
            shininess: shininess,
            shading: shading } );

    DynamicsVisualizer.Materials["lava"] = new THREE.MeshPhongMaterial(
        {   map: lavaTexture,
            bumpMap: lavaTexture,
            bumpScale: 0.5,
            color: 0xffffff,
            ambient: 0x777777,
            specular: 0x333333,
            shininess: shininess,
            shading: shading } );

    DynamicsVisualizer.Materials["moon"] = new THREE.MeshPhongMaterial(
        {   map: moonTexture,
            bumpMap: moonTexture,
            bumpScale: 0.0001,
            color: 0xffffff,
            ambient: 0x777777,
            specular: 0x333333,
            shininess: 0,
            shading: shading } );

    DynamicsVisualizer.Materials["earth"] = new THREE.MeshPhongMaterial(
        {   map: earthTexture,
            color: 0xffffff,
            ambient: 0x777777,
            specular: 0x333333,
            shininess: shininess,
            shading: shading } );

}
loadMaterials();
<|endoftext|>


<commit_before>/** Copyright 2013-2018 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */

const _ = require('lodash');
const matchesToken = require('chevrotain').tokenMatcher;
const JDLParser = require('./jdl_parser');
const LexerTokens = require('./lexer').tokens;
const checkConfigKeys = require('./self_checks/parsing_system_checker').checkConfigKeys;

const constantPattern = /^[A-Z_]+$/;
const entityNamePattern = /^[A-Z][A-Za-z0-9]*$/;
const typeNamePattern = /^[A-Z][A-Za-z0-9]*$/;
const enumNamePattern = /^[A-Z][A-Za-z0-9]*$/;
const enumPropNamePattern = /^[A-Z][A-Za-z0-9_]*$/;
const methodNamePattern = /^[A-Za-z][A-Za-z0-9-]*$/;
const jhiPrefixNamePattern = /^[A-Za-z][A-Za-z0-9-_]*$/;
const alphabetic = /^[A-Za-z]+$/;
const alphabeticLower = /^[a-z]+$/;
const alphanumeric = /^[A-Za-z][A-Za-z0-9]*$/;
const alphanumericDash = /^[A-Za-z][A-Za-z0-9-]*$/;

const configPropsValidations = {
  APPLICATION_TYPE:
    {
      type: 'NAME',
      pattern: alphabeticLower,
      msg: 'applicationType property'
    },
  AUTHENTICATION_TYPE:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'authenticationType property'
    },
  BASE_NAME:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'baseName property'
    },
  BUILD_TOOL:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'buildTool property'
    },
  CACHE_PROVIDER:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'cacheProvider property'
    },
  CLIENT_FRAMEWORK:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'clientFramework property'
    },
  CLIENT_PACKAGE_MANAGER:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'clientPackageManager property'
    },
  DATABASE_TYPE:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'databaseType property'
    },
  DEV_DATABASE_TYPE:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'devDatabaseType property'
    },
  ENABLE_HIBERNATE_CACHE: { type: 'BOOLEAN' },
  ENABLE_SWAGGER_CODEGEN: { type: 'BOOLEAN' },
  ENABLE_TRANSLATION: { type: 'BOOLEAN' },
  FRONT_END_BUILDER:
    {
      type: 'NAME',
      pattern: alphabetic,
      msg: 'frontendBuilder property'
    },
  JHIPSTER_VERSION: { type: 'STRING' },
  JHI_PREFIX:
    {
      type: 'NAME',
      pattern: jhiPrefixNamePattern,
      msg: 'jhiPrefix property'
    },
  LANGUAGES: { type: 'list', pattern: alphabeticLower, msg: 'languages property' },
  MESSAGE_BROKER:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'messageBroker property'
    },
  NATIVE_LANGUAGE:
    {
      type: 'NAME',
      pattern: alphabeticLower,
      msg: 'nativeLanguage property'
    },
  PACKAGE_NAME:
    {
      type: 'qualifiedName',
      pattern: alphabeticLower,
      msg: 'packageName property'
    },
  PROD_DATABASE_TYPE:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'prodDatabaseType property'
    },
  SEARCH_ENGINE:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'searchEngine property'
    },
  SERVER_PORT: { type: 'INTEGER' },
  SERVICE_DISCOVERY_TYPE:
    {
      type: 'NAME',
      pattern: alphanumeric,
      msg: 'serviceDiscoveryType property'
    },
  SKIP_CLIENT: { type: 'BOOLEAN' },
  SKIP_SERVER: { type: 'BOOLEAN' },
  SKIP_USER_MANAGEMENT: { type: 'BOOLEAN' },
  TEST_FRAMEWORKS:
    {
      type: 'list',
      pattern: alphanumeric,
      msg: 'testFrameworks property'
    },
  UAA_BASE_NAME: { type: 'STRING' },
  USE_SASS: { type: 'BOOLEAN' },
  WEBSOCKET:
    {
      type: 'NAME',
      pattern: alphanumericDash,
      msg: 'websocket property'
    }
};

module.exports = {
  performAdditionalSyntaxChecks
};

const parser = JDLParser.getParser();
parser.parse();
const BaseJDLCSTVisitorWithDefaults = parser.getBaseCstVisitorConstructorWithDefaults();

class JDLSyntaxValidatorVisitor extends BaseJDLCSTVisitorWithDefaults {
  constructor() {
    super();
    this.validateVisitor();

    this.errors = [];
  }

  checkNameSyntax(token, expectedPattern, errMsgPrefix) {
    if (!expectedPattern.test(token.image)) {
      this.errors.push({
        message: `${errMsgPrefix} name must match: ${trimAnchors(
          expectedPattern.toString()
        )}`,
        token
      });
    }
  }

  checkIsSingleName(fqnCstNode) {
    // A Boolean is allowed as a single name as it is a keyword.
    // Other keywords do not need special handling as they do not explicitly appear in the rule
    // of config values
    if (fqnCstNode.tokenType && fqnCstNode.tokenType.CATEGORIES.includes(LexerTokens.BOOLEAN)) {
      return false;
    }

    const dots = fqnCstNode.children.DOT;
    if (dots && dots.length >= 1) {
      this.errors.push({
        message: 'A single name is expected, but found a fully qualified name.',
        token: getFirstToken(fqnCstNode)
      });
      return false;
    }
    return true;
  }

  checkExpectedValueType(expected, actual) {
    switch (expected) {
    case 'NAME':
      if (actual.name !== 'qualifiedName'
        // a Boolean (true/false) is also a valid name.
        && (actual.tokenType && !_.includes(actual.tokenType.CATEGORIES, LexerTokens.BOOLEAN))) {
        this.errors.push({
          message: `A name is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return this.checkIsSingleName(actual);

    case 'qualifiedName':
      if (actual.name !== 'qualifiedName') {
        this.errors.push({
          message: `A fully qualified name is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    case 'list':
      if (actual.name !== 'list') {
        this.errors.push({
          message: `An array of names is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    case 'INTEGER':
      if (actual.tokenType !== LexerTokens.INTEGER) {
        this.errors.push({
          message: `An integer literal is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    case 'STRING':
      if (actual.tokenType !== LexerTokens.STRING) {
        this.errors.push({
          message: `A string literal is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    case 'BOOLEAN':
      if (!matchesToken(actual, LexerTokens.BOOLEAN)) {
        this.errors.push({
          message: `A boolean literal is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    default:
      throw Error('Non Exhaustive Match');
    }
  }

  checkConfigPropSyntax(key, value) {
    const propertyName = key.tokenType.tokenName;
    const validation = configPropsValidations[propertyName];
    if (!validation) {
      throw Error('Non Exhaustive Match');
    }

    if (this.checkExpectedValueType(validation.type, value) && validation.pattern && value.children.NAME) {
      value.children.NAME.forEach(nameTok => this.checkNameSyntax(nameTok, validation.pattern, validation.msg));
    }
  }

  constantDeclaration(ctx) {
    super.constantDeclaration(ctx);
    this.checkNameSyntax(ctx.NAME[0], constantPattern, 'Constant');
  }

  entityDeclaration(ctx) {
    super.entityDeclaration(ctx);
    this.checkNameSyntax(ctx.NAME[0], entityNamePattern, 'Entity');
  }

  fieldDeclaration(ctx) {
    super.fieldDeclaration(ctx);
    this.checkNameSyntax(ctx.NAME[0], alphanumeric, 'fieldName');
  }

  type(ctx) {
    super.type(ctx);
    this.checkNameSyntax(ctx.NAME[0], typeNamePattern, 'typeName');
  }

  minMaxValidation(ctx) {
    super.minMaxValidation(ctx);
    if (ctx.NAME) {
      this.checkNameSyntax(ctx.NAME[0], constantPattern, 'constant');
    }
  }

  relationshipSide(ctx) {
    super.relationshipSide(ctx);
    this.checkNameSyntax(ctx.NAME[0], entityNamePattern, 'Entity');

    if (ctx.InjectedField) {
      this.checkNameSyntax(
        ctx.InjectedField[0],
        alphanumeric,
        'InjectedField'
      );
      if (ctx.InjectedFieldParam) {
        this.checkNameSyntax(
          ctx.InjectedFieldParam[0],
          alphanumeric,
          'InjectedField'
        );
      }
    }
  }

  enumDeclaration(ctx) {
    super.enumDeclaration(ctx);
    this.checkNameSyntax(ctx.NAME[0], enumNamePattern, 'Enum');
  }

  enumPropList(ctx) {
    super.enumPropList(ctx);
    ctx.NAME.forEach((nameToken) => {
      this.checkNameSyntax(nameToken, enumPropNamePattern, 'Enum Property');
    });
  }

  entityList(ctx) {
    super.entityList(ctx);
    if (ctx.NAME) {
      ctx.NAME.forEach((nameToken) => {
        this.checkNameSyntax(nameToken, entityNamePattern, 'Entity');
      });
    }

    if (ctx.Method) {
      this.checkNameSyntax(ctx.Method[0], methodNamePattern, 'Method');
    }
  }

  exclusion(ctx) {
    super.exclusion(ctx);
    ctx.NAME.forEach((nameToken) => {
      this.checkNameSyntax(nameToken, entityNamePattern, 'Entity');
    });
  }

  filterDef(ctx) {
    if (ctx.NAME) {
      ctx.NAME.forEach((nameToken) => {
        this.checkNameSyntax(nameToken, entityNamePattern, 'Entity');
      });
    }
  }

  applicationConfigDeclaration(ctx) {
    this.visit(ctx.configValue, ctx.CONFIG_KEY[0]);
  }

  configValue(ctx, configKey) {
    const configValue = _.first(_.first(_.values(ctx)));
    this.checkConfigPropSyntax(configKey, configValue);
  }
}

function performAdditionalSyntaxChecks(cst) {
  const syntaxValidatorVisitor = new JDLSyntaxValidatorVisitor();
  syntaxValidatorVisitor.visit(cst);
  return syntaxValidatorVisitor.errors;
}

checkConfigKeys(LexerTokens, _.keys(configPropsValidations));

function trimAnchors(str) {
  return str.replace(/^\^/, '')
    .replace(/\$$/, '');
}

function getFirstToken(tokOrCstNode) {
  if (tokOrCstNode.tokenType) {
    return tokOrCstNode;
  }

  // CST Node - - assumes no nested CST Nodes, only terminals
  return _.flatten(_.values(tokOrCstNode.children))
    .reduce(
      (firstTok, nextTok) => (firstTok.startOffset > nextTok.startOffset ? nextTok : firstTok),
      { startOffset: Infinity }
    );
}
<commit_msg>Cleaned up the validator<commit_after>/** Copyright 2013-2018 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */

const _ = require('lodash');
const matchesToken = require('chevrotain').tokenMatcher;
const JDLParser = require('./jdl_parser');
const LexerTokens = require('./lexer').tokens;
const checkConfigKeys = require('./self_checks/parsing_system_checker').checkConfigKeys;

const CONSTANT_PATTERN = /^[A-Z_]+$/;
const ENTITY_NAME_PATTERN = /^[A-Z][A-Za-z0-9]*$/;
const TYPE_NAME_PATTERN = /^[A-Z][A-Za-z0-9]*$/;
const ENUM_NAME_PATTERN = /^[A-Z][A-Za-z0-9]*$/;
const ENUM_PROP_NAME_PATTERN = /^[A-Z][A-Za-z0-9_]*$/;
const METHOD_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9-]*$/;
const JHI_PREFIX_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9-_]*$/;
const ALPHABETIC = /^[A-Za-z]+$/;
const ALPHABETIC_LOWER = /^[a-z]+$/;
const ALPHANUMERIC = /^[A-Za-z][A-Za-z0-9]*$/;
const ALPHANUMERIC_DASH = /^[A-Za-z][A-Za-z0-9-]*$/;

const configPropsValidations = {
  APPLICATION_TYPE:
    {
      type: 'NAME',
      pattern: ALPHABETIC_LOWER,
      msg: 'applicationType property'
    },
  AUTHENTICATION_TYPE:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'authenticationType property'
    },
  BASE_NAME:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'baseName property'
    },
  BUILD_TOOL:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'buildTool property'
    },
  CACHE_PROVIDER:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'cacheProvider property'
    },
  CLIENT_FRAMEWORK:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'clientFramework property'
    },
  CLIENT_PACKAGE_MANAGER:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'clientPackageManager property'
    },
  DATABASE_TYPE:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'databaseType property'
    },
  DEV_DATABASE_TYPE:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'devDatabaseType property'
    },
  ENABLE_HIBERNATE_CACHE: { type: 'BOOLEAN' },
  ENABLE_SWAGGER_CODEGEN: { type: 'BOOLEAN' },
  ENABLE_TRANSLATION: { type: 'BOOLEAN' },
  FRONT_END_BUILDER:
    {
      type: 'NAME',
      pattern: ALPHABETIC,
      msg: 'frontendBuilder property'
    },
  JHIPSTER_VERSION: { type: 'STRING' },
  JHI_PREFIX:
    {
      type: 'NAME',
      pattern: JHI_PREFIX_NAME_PATTERN,
      msg: 'jhiPrefix property'
    },
  LANGUAGES: { type: 'list', pattern: ALPHABETIC_LOWER, msg: 'languages property' },
  MESSAGE_BROKER:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'messageBroker property'
    },
  NATIVE_LANGUAGE:
    {
      type: 'NAME',
      pattern: ALPHABETIC_LOWER,
      msg: 'nativeLanguage property'
    },
  PACKAGE_NAME:
    {
      type: 'qualifiedName',
      pattern: ALPHABETIC_LOWER,
      msg: 'packageName property'
    },
  PROD_DATABASE_TYPE:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'prodDatabaseType property'
    },
  SEARCH_ENGINE:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'searchEngine property'
    },
  SERVER_PORT: { type: 'INTEGER' },
  SERVICE_DISCOVERY_TYPE:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC,
      msg: 'serviceDiscoveryType property'
    },
  SKIP_CLIENT: { type: 'BOOLEAN' },
  SKIP_SERVER: { type: 'BOOLEAN' },
  SKIP_USER_MANAGEMENT: { type: 'BOOLEAN' },
  TEST_FRAMEWORKS:
    {
      type: 'list',
      pattern: ALPHANUMERIC,
      msg: 'testFrameworks property'
    },
  UAA_BASE_NAME: { type: 'STRING' },
  USE_SASS: { type: 'BOOLEAN' },
  WEBSOCKET:
    {
      type: 'NAME',
      pattern: ALPHANUMERIC_DASH,
      msg: 'websocket property'
    }
};

module.exports = {
  performAdditionalSyntaxChecks
};

const parser = JDLParser.getParser();
parser.parse();
const BaseJDLCSTVisitorWithDefaults = parser.getBaseCstVisitorConstructorWithDefaults();

class JDLSyntaxValidatorVisitor extends BaseJDLCSTVisitorWithDefaults {
  constructor() {
    super();
    this.validateVisitor();

    this.errors = [];
  }

  checkNameSyntax(token, expectedPattern, errorMessagePrefix) {
    if (!expectedPattern.test(token.image)) {
      this.errors.push({
        message: `The ${errorMessagePrefix} name must match: ${trimAnchors(
          expectedPattern.toString()
        )}`,
        token
      });
    }
  }

  checkIsSingleName(fqnCstNode) {
    // A Boolean is allowed as a single name as it is a keyword.
    // Other keywords do not need special handling as they do not explicitly appear in the rule
    // of config values
    if (fqnCstNode.tokenType && fqnCstNode.tokenType.CATEGORIES.includes(LexerTokens.BOOLEAN)) {
      return false;
    }

    const dots = fqnCstNode.children.DOT;
    if (dots && dots.length >= 1) {
      this.errors.push({
        message: 'A single name is expected, but found a fully qualified name.',
        token: getFirstToken(fqnCstNode)
      });
      return false;
    }
    return true;
  }

  checkExpectedValueType(expected, actual) {
    switch (expected) {
    case 'NAME':
      if (actual.name !== 'qualifiedName'
        // a Boolean (true/false) is also a valid name.
        && (actual.tokenType && !_.includes(actual.tokenType.CATEGORIES, LexerTokens.BOOLEAN))) {
        this.errors.push({
          message: `A name is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return this.checkIsSingleName(actual);

    case 'qualifiedName':
      if (actual.name !== 'qualifiedName') {
        this.errors.push({
          message: `A fully qualified name is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    case 'list':
      if (actual.name !== 'list') {
        this.errors.push({
          message: `An array of names is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    case 'INTEGER':
      if (actual.tokenType !== LexerTokens.INTEGER) {
        this.errors.push({
          message: `An integer literal is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    case 'STRING':
      if (actual.tokenType !== LexerTokens.STRING) {
        this.errors.push({
          message: `A string literal is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    case 'BOOLEAN':
      if (!matchesToken(actual, LexerTokens.BOOLEAN)) {
        this.errors.push({
          message: `A boolean literal is expected, but found: "${getFirstToken(actual).image}"`,
          token: getFirstToken(actual)
        });
        return false;
      }
      return true;

    default:
      throw Error('Non Exhaustive Match');
    }
  }

  checkConfigPropSyntax(key, value) {
    const propertyName = key.tokenType.tokenName;
    const validation = configPropsValidations[propertyName];
    if (!validation) {
      throw Error('Non Exhaustive Match');
    }

    if (this.checkExpectedValueType(validation.type, value) && validation.pattern && value.children.NAME) {
      value.children.NAME.forEach(nameTok => this.checkNameSyntax(nameTok, validation.pattern, validation.msg));
    }
  }

  constantDeclaration(ctx) {
    super.constantDeclaration(ctx);
    this.checkNameSyntax(ctx.NAME[0], CONSTANT_PATTERN, 'constant');
  }

  entityDeclaration(ctx) {
    super.entityDeclaration(ctx);
    this.checkNameSyntax(ctx.NAME[0], ENTITY_NAME_PATTERN, 'entity');
  }

  fieldDeclaration(ctx) {
    super.fieldDeclaration(ctx);
    this.checkNameSyntax(ctx.NAME[0], ALPHANUMERIC, 'fieldName');
  }

  type(ctx) {
    super.type(ctx);
    this.checkNameSyntax(ctx.NAME[0], TYPE_NAME_PATTERN, 'typeName');
  }

  minMaxValidation(ctx) {
    super.minMaxValidation(ctx);
    if (ctx.NAME) {
      this.checkNameSyntax(ctx.NAME[0], CONSTANT_PATTERN, 'constant');
    }
  }

  relationshipSide(ctx) {
    super.relationshipSide(ctx);
    this.checkNameSyntax(ctx.NAME[0], ENTITY_NAME_PATTERN, 'entity');

    if (ctx.InjectedField) {
      this.checkNameSyntax(
        ctx.InjectedField[0],
        ALPHANUMERIC,
        'injectedField'
      );
      if (ctx.InjectedFieldParam) {
        this.checkNameSyntax(
          ctx.InjectedFieldParam[0],
          ALPHANUMERIC,
          'injectedField'
        );
      }
    }
  }

  enumDeclaration(ctx) {
    super.enumDeclaration(ctx);
    this.checkNameSyntax(ctx.NAME[0], ENUM_NAME_PATTERN, 'enum');
  }

  enumPropList(ctx) {
    super.enumPropList(ctx);
    ctx.NAME.forEach((nameToken) => {
      this.checkNameSyntax(nameToken, ENUM_PROP_NAME_PATTERN, 'enum property');
    });
  }

  entityList(ctx) {
    super.entityList(ctx);
    if (ctx.NAME) {
      ctx.NAME.forEach((nameToken) => {
        this.checkNameSyntax(nameToken, ENTITY_NAME_PATTERN, 'entity');
      });
    }

    if (ctx.Method) {
      this.checkNameSyntax(ctx.Method[0], METHOD_NAME_PATTERN, 'method');
    }
  }

  exclusion(ctx) {
    super.exclusion(ctx);
    ctx.NAME.forEach((nameToken) => {
      this.checkNameSyntax(nameToken, ENTITY_NAME_PATTERN, 'entity');
    });
  }

  filterDef(ctx) {
    if (ctx.NAME) {
      ctx.NAME.forEach((nameToken) => {
        this.checkNameSyntax(nameToken, ENTITY_NAME_PATTERN, 'entity');
      });
    }
  }

  applicationConfigDeclaration(ctx) {
    this.visit(ctx.configValue, ctx.CONFIG_KEY[0]);
  }

  configValue(ctx, configKey) {
    const configValue = _.first(_.first(_.values(ctx)));
    this.checkConfigPropSyntax(configKey, configValue);
  }
}

function performAdditionalSyntaxChecks(cst) {
  const syntaxValidatorVisitor = new JDLSyntaxValidatorVisitor();
  syntaxValidatorVisitor.visit(cst);
  return syntaxValidatorVisitor.errors;
}

checkConfigKeys(LexerTokens, _.keys(configPropsValidations));

function trimAnchors(str) {
  return str.replace(/^\^/, '')
    .replace(/\$$/, '');
}

function getFirstToken(tokOrCstNode) {
  if (tokOrCstNode.tokenType) {
    return tokOrCstNode;
  }

  // CST Node - - assumes no nested CST Nodes, only terminals
  return _.flatten(_.values(tokOrCstNode.children))
    .reduce(
      (firstTok, nextTok) => (firstTok.startOffset > nextTok.startOffset ? nextTok : firstTok),
      { startOffset: Infinity }
    );
}
<|endoftext|>


<commit_before>'use babel'

import {TextEditor, Emitter, CompositeDisposable} from 'atom'

export default class EditorLinter {
  constructor(editor) {
    if (!(editor instanceof TextEditor)) {
      throw new Error('Given editor is not really an editor')
    }

    this.editor = editor
    this.emitter = new Emitter()
    this.editorMarkers = new WeakMap()
    this.gutter = null
    this.subscriptions = new CompositeDisposable

    this.subscriptions.add(atom.config.observe('linter.underlineIssues', underlineIssues =>
      this.underlineIssues = underlineIssues
    ))
    this.subscriptions.add(this.editor.onDidDestroy(() =>
      this.destroy()
    ))
    this.subscriptions.add(this.editor.onDidSave(() =>
      this.emitter.emit('should-lint', false)
    ))
    this.subscriptions.add(this.editor.onDidChangeCursorPosition(({oldBufferPosition, newBufferPosition}) => {
      if (newBufferPosition.row !== oldBufferPosition.row) {
        this.emitter.emit('should-update-line-messages')
      }
      this.emitter.emit('should-update-bubble')
    }))
    this.subscriptions.add(atom.config.observe('linter.gutterEnabled', () =>
      this.handleGutter()
    ))
    // Using onDidChange here 'cause the same function is invoked above
    this.subscriptions.add(atom.config.onDidChange('linter.gutterPosition', () =>
      this.handleGutter()
    ))

    // Atom invokes the onDidStopChanging callback immediately on creation. So we wait a moment
    setImmediate(() => {
      this.subscriptions.add(this.editor.onDidStopChanging(() =>
        this.emitter.emit('should-lint', true)
      ))
    })
  }

  handleGutter() {
    const status = atom.config.get('linter.gutterEnabled')

    if (this.gutter !== null) this.removeGutter()
    if (status) this.addGutter()
  }

  addGutter() {
    const position = atom.config.get('linter.gutterPosition')
    this.gutter = this.editor.addGutter({
      name: 'linter',
      priority: position === 'Left' ? -100 : 100
    })
  }

  removeGutter() {
    if (this.gutter !== null) {
      this.gutter.destroy()
      this.gutter = null
    }
  }

  addMessage(message) {
    const marker = this.editor.markBufferRange(message.range, {invalidate: 'inside'})
    this.editorMarkers.set(message, marker)
    this.editor.decorateMarker(marker, {
      type: 'line-number',
      class: `linter-highlight ${message.class}`
    })
    if (this.underlineIssues) {
      this.editor.decorateMarker(marker, {
        type: 'highlight',
        class: `linter-highlight ${message.class}`
      })
    }
  }

  removeMessage(message) {
    if (this.editorMarkers.has(message)) {
      const marker = this.editorMarkers.get(message)
      marker.destroy()
      this.editorMarkers.delete(marker)
    }
  }

  lint(onChange = false) {
    this.emitter.emit('should-lint', onChange)
  }

  onShouldUpdateBubble(callback) {
    return this.emitter.on('should-update-bubble', callback)
  }

  onShouldUpdateLineMessages(callback) {
    return this.emitter.on('should-update-line-messages', callback)
  }

  onShouldLint(callback) {
    return this.emitter.on('should-lint', callback)
  }

  onDidDestroy(callback) {
    return this.emitter.on('did-destroy', callback)
  }

  destroy() {
    this.emitter.emit('did-destroy')
    this.dispose()
  }

  dispose() {
    if (this.editorMarkers.size) {
      this.editorMarkers.forEach(marker => marker.destroy())
    }
    this.removeGutter()
    this.subscriptions.dispose()
  }
}
<commit_msg>:new: Add EditorLinter::{gutterMarkers, messages}<commit_after>'use babel'

import {TextEditor, Emitter, CompositeDisposable} from 'atom'

export default class EditorLinter {
  constructor(editor) {
    if (!(editor instanceof TextEditor)) {
      throw new Error('Given editor is not really an editor')
    }

    this.editor = editor
    this.emitter = new Emitter()
    this.messages = new Set()
    this.gutterMarkers = new WeakMap()
    this.editorMarkers = new WeakMap()
    this.gutter = null
    this.subscriptions = new CompositeDisposable

    this.subscriptions.add(atom.config.observe('linter.underlineIssues', underlineIssues =>
      this.underlineIssues = underlineIssues
    ))
    this.subscriptions.add(this.editor.onDidDestroy(() =>
      this.destroy()
    ))
    this.subscriptions.add(this.editor.onDidSave(() =>
      this.emitter.emit('should-lint', false)
    ))
    this.subscriptions.add(this.editor.onDidChangeCursorPosition(({oldBufferPosition, newBufferPosition}) => {
      if (newBufferPosition.row !== oldBufferPosition.row) {
        this.emitter.emit('should-update-line-messages')
      }
      this.emitter.emit('should-update-bubble')
    }))
    this.subscriptions.add(atom.config.observe('linter.gutterEnabled', () =>
      this.handleGutter()
    ))
    // Using onDidChange here 'cause the same function is invoked above
    this.subscriptions.add(atom.config.onDidChange('linter.gutterPosition', () =>
      this.handleGutter()
    ))

    // Atom invokes the onDidStopChanging callback immediately on creation. So we wait a moment
    setImmediate(() => {
      this.subscriptions.add(this.editor.onDidStopChanging(() =>
        this.emitter.emit('should-lint', true)
      ))
    })
  }

  handleGutter() {
    const status = atom.config.get('linter.gutterEnabled')

    if (this.gutter !== null) this.removeGutter()
    if (status) this.addGutter()
  }

  addGutter() {
    const position = atom.config.get('linter.gutterPosition')
    this.gutter = this.editor.addGutter({
      name: 'linter',
      priority: position === 'Left' ? -100 : 100
    })
  }

  removeGutter() {
    if (this.gutter !== null) {
      this.gutter.destroy()
      this.gutter = null
    }
  }

  addMessage(message) {
    this.messages.add(message)
    const marker = this.editor.markBufferRange(message.range, {invalidate: 'inside'})
    this.editorMarkers.set(message, marker)
    this.editor.decorateMarker(marker, {
      type: 'line-number',
      class: `linter-highlight ${message.class}`
    })
    if (this.underlineIssues) {
      this.editor.decorateMarker(marker, {
        type: 'highlight',
        class: `linter-highlight ${message.class}`
      })
    }
  }

  removeMessage(message) {
    this.messages.delete(message)
    if (this.editorMarkers.has(message)) {
      const marker = this.editorMarkers.get(message)
      marker.destroy()
      this.editorMarkers.delete(marker)
    }
  }

  lint(onChange = false) {
    this.emitter.emit('should-lint', onChange)
  }

  onShouldUpdateBubble(callback) {
    return this.emitter.on('should-update-bubble', callback)
  }

  onShouldUpdateLineMessages(callback) {
    return this.emitter.on('should-update-line-messages', callback)
  }

  onShouldLint(callback) {
    return this.emitter.on('should-lint', callback)
  }

  onDidDestroy(callback) {
    return this.emitter.on('did-destroy', callback)
  }

  destroy() {
    this.emitter.emit('did-destroy')
    this.dispose()
  }

  dispose() {
    if (this.editorMarkers.size) {
      this.editorMarkers.forEach(marker => marker.destroy())
      this.editorMarkers.clear()
    }
    if (this.gutterMarkers.size) {
      this.gutterMarkers.forEach(marker => marker.destroy())
      this.gutterMarkers.clear()
    }
    this.removeGutter()
    this.subscriptions.dispose()
    this.messages.clear()
  }
}
<|endoftext|>


<commit_before>var request = require('request');
var util = require('util');

var ElasticClient = function(options)
{
	options = options || {};
	var host = options.host? options.host : "localhost";
	var port = options.port? options.port : 9200;
	this.url = 'http://' + host + ':' + port,
	this.index = options.index? options.index : 'main';
	this.type = options.type? options.type : 'main';
};

ElasticClient.prototype.status = function(callback) {
	 var requestObj = {
	 	url : this.url + '/_status',
	 	method : 'GET'
	 }

	 this.processRequest(requestObj, callback);
};

ElasticClient.prototype.indexStatus = function(callback) {
    var requestObj = {
        url: this.url + '/' + this.index + '/_status',
        method : 'GET'
    };

    this.processRequest(requestObj, callback);
};

ElasticClient.prototype.createIndex = function(name, indexDef, callback) {
	if (!callback && typeof indexDef === 'function') {
		callback = indexDef;
	}

	if(name && typeof name === 'string')
	{
		var requestObj = {
			url : this.url + '/' + name,
			method : 'PUT'
		};

		if(indexDef)
		{
			requestObj.json = indexDef;
		}

		this.processRequest(requestObj, callback);
	}
	else
		throw new Error('name must be not empty string')
};

ElasticClient.prototype.deleteIndex = function(name, callback) {

	if(name && typeof name === 'string')
	{
		var requestObj = {
				url : this.url + '/' + name,
				method : 'DELETE'
		};
		this.processRequest(requestObj,callback);
	}
	else
		throw new Error('name must be not empty string');

};

/*ElasticClient.prototype.indexStatus = function(name, callback) {
	if(name && typeof name === 'string')
	{
		var url = this.url + '/' + name + '/_status';
		request(url,function(err, response, body){
			if (err) {callback(err, null);}
			else {
				if (response.statusCode == 200) {
					callback(null, body);
				}
				else {
					callback(new Error('HTTP error code:' + response.statusCode ), body);
				}
			}
		});
	}
	else
		throw new Error('name must be not empty string');
};*/

ElasticClient.prototype.indexObject = function(object, id, parent, callback) {
	if (typeof id === 'function') {
		callback = id;
		id = null;
        parent = null;
	}

    if(typeof parent === 'function') {
        callback = parent;
        parent = null;
    }

	var requestObject =  {
		url : this.url + '/' + this.index + '/' + this.type + (id ? '/' + id : '') + (parent? '?parent=' + parent : ''),
		method : 'POST',
		json : object
	};

	this.processRequest(requestObject, callback);
};

ElasticClient.prototype.searchExactTerm = function(field, term, boost, callback) {
	if (typeof boost === 'function') {
		callback = boost;
		boost = undefined;
	}

	var termQuery = require('./query/termQuery');
	var query = new termQuery(field, term, boost);
	this.query(query,callback);
};

ElasticClient.prototype.searchText = function(field, text, options, callback) {
	if (typeof options === 'function') {
		callback = options;
		options = null;
	}

	var mQuery = require('./query/matchQuery');
	var query = new mQuery(field, text, options);
	this.query(query, callback);
};

ElasticClient.prototype.query = function(query, callback) {
	var requestObject = {
		url : this.url + '/' + this.index + '/_search',
		method : 'POST',
		json : query.toJson()
	}

	this.processRequest(requestObject, callback);
};

ElasticClient.prototype.processRequest = function(requestObject, callback) {
	request(requestObject, function(err, response, body)
		{
			if (err) { callback(err, null); }
			else {
				if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204) {
					callback(null, body);
				}
				else
				{
					callback(new Error('Http error:' + response.statusCode), body);
				}
			}
		});
};

ElasticClient.prototype.analyze = function(text, options, callback) {

	if (typeof options === 'function') {
		callback = options;
		options = null;
	}

	var query = '';
	if(options)
	{
		if (options.analyzer) { query += 'analyzer=' + options.analyzer}
		if (options.tokenizer) {
			if (query) { query += '&'}
			query += 'tokenizer=' + options.tokenizer;
		}

		if (options.filter) {
			if(query) { query += '&' }

			query += 'filter=' + options.filter;
		}
	}

	var requestObject = {
		url : this.url + '/_analyze' + (query? '?' + query : ''),
		method : 'GET',
		body : text
	};

	this.processRequest(requestObject, callback);
};

ElasticClient.prototype.indexBulk = function(objects, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options = null;
    }

    if(!objects || objects.length == 0)
        throw new Error('objects parameter must be not empty array');

    var requestData = '';
    var indexTemplate = '{ "index" : { "_index" : "' + this.index + '", "_type" : "' + this.type + '" %s} }';

    for(var o in objects) {
        var indexMeta = ''
        if(options)
        {
            if (options.idfield) {
                var _indexId = util.format(', "_id" : "%s"', objects[o][options.idfield]);
                indexMeta = util.format(indexTemplate, _indexId);
            }
            else {
                indexMeta = util.format(indexTemplate, '');
            }
        }
        else
            indexMeta = util.format(indexTemplate, '');
        requestData += indexMeta + '\n';
        requestData += JSON.stringify(objects[o]) + '\n';
    }

    var requestObject = {
        url : this.url + '/_bulk',
        method : 'POST',
        body : requestData
    };

    this.processRequest(requestObject, callback);
};

ElasticClient.prototype.updateBulk = function(objects, options, callback) {
    if(!objects || typeof objects != 'Array') {
        throw new Error('objects must be not empty array');
    }

    if(typeof options === 'function') {
        callback = options;
        options = { };
    }

    //TODO walking on objects and by ID index object into elastic
};

ElasticClient.prototype.urlSearch = function(columns, values, callback) {
    if (!columns ||  !Array.isArray(columns) || columns.length == 0)
        throw new Error('columns must be not empty array');
    if(!values || !Array.isArray(values) || values.length == 0 || columns.length != values.length)
        throw new Error('values must be not empty array with length equals to columns');
    if(typeof callback !== 'function')
        throw new Error('callback is needed');

    var qs = '';
    for(var i = 0; i < columns.length; i++)
    {
        qs += util.format('+%s:%s ', columns[i], values[i]);
    }

    var url = this.url + '/' + this.index + '/' + this.type + '/_search?q=' + qs;

    var requestObject = {
        url : url,
        method : 'GET'
    }

    this.processRequest(requestObject, callback);
};

ElasticClient.prototype.getDoc = function(docId, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options = {};
    }

    var requestObject = {
        url : this.url + '/' + this.index + '/' + this.type + '/' + docId,
        method : 'GET'
    };

    this.processRequest(requestObject, callback);
};

/*ElasticClient.prototy.getDateAggregation = function(from, to, step, units, callback) {
    if(typeof step == 'function') {
        callback = step;
        step = 1;
    }
};*/

ElasticClient.prototype.runQuery = function(query, options, callback) {
    if(typeof query == 'function') {
        callback = query;
        query = {
            "query" : {
                "match_all" : {}
            }
        };
        options = {};
    }

    if(typeof options == 'function') {
        callback = options;
        options = {};
    }

    var index = options.index? options.index : this.index;
    var type = options.type? options.type : this.type;

    var url = this.url;
    if(!options.avoid_index) {
        url += '/' + index;
    } else if(!options.avoid_type) {
        url += '/' + type;
    }

    url += '/_search';

    var requestObject = {
        url : url,
        method : 'POST',
        json : query
    }

    this.processRequest(requestObject, callback);
};
exports = module.exports;
exports.ElasticClient = ElasticClient;
<commit_msg>Fix bug on runQuery for avoiding type any time.<commit_after>var request = require('request');
var util = require('util');

var ElasticClient = function(options)
{
	options = options || {};
	var host = options.host? options.host : "localhost";
	var port = options.port? options.port : 9200;
	this.url = 'http://' + host + ':' + port,
	this.index = options.index? options.index : 'main';
	this.type = options.type? options.type : 'main';
};

ElasticClient.prototype.status = function(callback) {
	 var requestObj = {
	 	url : this.url + '/_status',
	 	method : 'GET'
	 }

	 this.processRequest(requestObj, callback);
};

ElasticClient.prototype.indexStatus = function(callback) {
    var requestObj = {
        url: this.url + '/' + this.index + '/_status',
        method : 'GET'
    };

    this.processRequest(requestObj, callback);
};

ElasticClient.prototype.createIndex = function(name, indexDef, callback) {
	if (!callback && typeof indexDef === 'function') {
		callback = indexDef;
	}

	if(name && typeof name === 'string')
	{
		var requestObj = {
			url : this.url + '/' + name,
			method : 'PUT'
		};

		if(indexDef)
		{
			requestObj.json = indexDef;
		}

		this.processRequest(requestObj, callback);
	}
	else
		throw new Error('name must be not empty string')
};

ElasticClient.prototype.deleteIndex = function(name, callback) {

	if(name && typeof name === 'string')
	{
		var requestObj = {
				url : this.url + '/' + name,
				method : 'DELETE'
		};
		this.processRequest(requestObj,callback);
	}
	else
		throw new Error('name must be not empty string');

};

/*ElasticClient.prototype.indexStatus = function(name, callback) {
	if(name && typeof name === 'string')
	{
		var url = this.url + '/' + name + '/_status';
		request(url,function(err, response, body){
			if (err) {callback(err, null);}
			else {
				if (response.statusCode == 200) {
					callback(null, body);
				}
				else {
					callback(new Error('HTTP error code:' + response.statusCode ), body);
				}
			}
		});
	}
	else
		throw new Error('name must be not empty string');
};*/

ElasticClient.prototype.indexObject = function(object, id, parent, callback) {
	if (typeof id === 'function') {
		callback = id;
		id = null;
        parent = null;
	}

    if(typeof parent === 'function') {
        callback = parent;
        parent = null;
    }

	var requestObject =  {
		url : this.url + '/' + this.index + '/' + this.type + (id ? '/' + id : '') + (parent? '?parent=' + parent : ''),
		method : 'POST',
		json : object
	};

	this.processRequest(requestObject, callback);
};

ElasticClient.prototype.searchExactTerm = function(field, term, boost, callback) {
	if (typeof boost === 'function') {
		callback = boost;
		boost = undefined;
	}

	var termQuery = require('./query/termQuery');
	var query = new termQuery(field, term, boost);
	this.query(query,callback);
};

ElasticClient.prototype.searchText = function(field, text, options, callback) {
	if (typeof options === 'function') {
		callback = options;
		options = null;
	}

	var mQuery = require('./query/matchQuery');
	var query = new mQuery(field, text, options);
	this.query(query, callback);
};

ElasticClient.prototype.query = function(query, callback) {
	var requestObject = {
		url : this.url + '/' + this.index + '/_search',
		method : 'POST',
		json : query.toJson()
	}

	this.processRequest(requestObject, callback);
};

ElasticClient.prototype.processRequest = function(requestObject, callback) {
	request(requestObject, function(err, response, body)
		{
			if (err) { callback(err, null); }
			else {
				if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204) {
					callback(null, body);
				}
				else
				{
					callback(new Error('Http error:' + response.statusCode), body);
				}
			}
		});
};

ElasticClient.prototype.analyze = function(text, options, callback) {

	if (typeof options === 'function') {
		callback = options;
		options = null;
	}

	var query = '';
	if(options)
	{
		if (options.analyzer) { query += 'analyzer=' + options.analyzer}
		if (options.tokenizer) {
			if (query) { query += '&'}
			query += 'tokenizer=' + options.tokenizer;
		}

		if (options.filter) {
			if(query) { query += '&' }

			query += 'filter=' + options.filter;
		}
	}

	var requestObject = {
		url : this.url + '/_analyze' + (query? '?' + query : ''),
		method : 'GET',
		body : text
	};

	this.processRequest(requestObject, callback);
};

ElasticClient.prototype.indexBulk = function(objects, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options = null;
    }

    if(!objects || objects.length == 0)
        throw new Error('objects parameter must be not empty array');

    var requestData = '';
    var indexTemplate = '{ "index" : { "_index" : "' + this.index + '", "_type" : "' + this.type + '" %s} }';

    for(var o in objects) {
        var indexMeta = ''
        if(options)
        {
            if (options.idfield) {
                var _indexId = util.format(', "_id" : "%s"', objects[o][options.idfield]);
                indexMeta = util.format(indexTemplate, _indexId);
            }
            else {
                indexMeta = util.format(indexTemplate, '');
            }
        }
        else
            indexMeta = util.format(indexTemplate, '');
        requestData += indexMeta + '\n';
        requestData += JSON.stringify(objects[o]) + '\n';
    }

    var requestObject = {
        url : this.url + '/_bulk',
        method : 'POST',
        body : requestData
    };

    this.processRequest(requestObject, callback);
};

ElasticClient.prototype.updateBulk = function(objects, options, callback) {
    if(!objects || typeof objects != 'Array') {
        throw new Error('objects must be not empty array');
    }

    if(typeof options === 'function') {
        callback = options;
        options = { };
    }

    //TODO walking on objects and by ID index object into elastic
};

ElasticClient.prototype.urlSearch = function(columns, values, callback) {
    if (!columns ||  !Array.isArray(columns) || columns.length == 0)
        throw new Error('columns must be not empty array');
    if(!values || !Array.isArray(values) || values.length == 0 || columns.length != values.length)
        throw new Error('values must be not empty array with length equals to columns');
    if(typeof callback !== 'function')
        throw new Error('callback is needed');

    var qs = '';
    for(var i = 0; i < columns.length; i++)
    {
        qs += util.format('+%s:%s ', columns[i], values[i]);
    }

    var url = this.url + '/' + this.index + '/' + this.type + '/_search?q=' + qs;

    var requestObject = {
        url : url,
        method : 'GET'
    }

    this.processRequest(requestObject, callback);
};

ElasticClient.prototype.getDoc = function(docId, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options = {};
    }

    var requestObject = {
        url : this.url + '/' + this.index + '/' + this.type + '/' + docId,
        method : 'GET'
    };

    this.processRequest(requestObject, callback);
};

/*ElasticClient.prototy.getDateAggregation = function(from, to, step, units, callback) {
    if(typeof step == 'function') {
        callback = step;
        step = 1;
    }
};*/

ElasticClient.prototype.runQuery = function(query, options, callback) {
    if(typeof query == 'function') {
        callback = query;
        query = {
            "query" : {
                "match_all" : {}
            }
        };
        options = {};
    }

    if(typeof options == 'function') {
        callback = options;
        options = {};
    }

    var index = options.index? options.index : this.index;
    var type = options.type? options.type : this.type;

    var url = this.url;
    if(!options.avoid_index) {
        url += '/' + index;
    }

    if(!options.avoid_type) {
        url += '/' + type;
    }

    url += '/_search';

    var requestObject = {
        url : url,
        method : 'POST',
        json : query
    }

    this.processRequest(requestObject, callback);
};
exports = module.exports;
exports.ElasticClient = ElasticClient;
<|endoftext|>


<commit_before>/*jshint node: true*/
/**
 * @author lattmann / https://github.com/lattmann
 * @author pmeijer / https://github.com/pmeijer
 */

var config = require('./config.default');

config.server.port = 9001;

config.mongo.uri = 'mongodb://127.0.0.1:27017/webgme_tests';
config.mongo.options.server.poolSize = 2; // this is the default

config.blob.fsDir = './test-tmp/blob-storage';

config.executor.outputDir = './test-tmp/executor';
config.executor.workerRefreshInterval = 100;

config.server.log = {
    transports: [{
        transportType: 'Console',
        options: {
            level: 'error',
            colorize: true,
            timestamp: true,
            prettyPrint: true,
            handleExceptions: true,
            depth: 2
        }
    }, {
        transportType: 'File',
        options: {
            name: 'info-file',
            filename: './test-tmp/server.log',
            level: 'info',
            json: false
        }
    }, {
        transportType: 'File',
        options: {
            name: 'error-file',
            filename: './test-tmp/server-error.log',
            level: 'error',
            handleExceptions: true,
            json: false
        }
    }]
};

module.exports = config;<commit_msg>Update config.test.js<commit_after>/*jshint node: true*/
/**
 * @author lattmann / https://github.com/lattmann
 * @author pmeijer / https://github.com/pmeijer
 */

var config = require('./config.default');

config.server.port = 9001;

config.mongo.uri = 'mongodb://127.0.0.1:27017/webgme_tests';
config.mongo.options.server.poolSize = 5; // this is the default

config.blob.fsDir = './test-tmp/blob-storage';

config.executor.outputDir = './test-tmp/executor';
config.executor.workerRefreshInterval = 100;

config.server.log = {
    transports: [{
        transportType: 'Console',
        options: {
            level: 'error',
            colorize: true,
            timestamp: true,
            prettyPrint: true,
            handleExceptions: true,
            depth: 2
        }
    }, {
        transportType: 'File',
        options: {
            name: 'info-file',
            filename: './test-tmp/server.log',
            level: 'info',
            json: false
        }
    }, {
        transportType: 'File',
        options: {
            name: 'error-file',
            filename: './test-tmp/server-error.log',
            level: 'error',
            handleExceptions: true,
            json: false
        }
    }]
};

module.exports = config;
<|endoftext|>


<commit_before>/*
 * Flush stats to ElasticSearch (http://www.elasticsearch.org/)
 *
 * To enable this backend, include 'elastic' in the backends
 * configuration array:
 *
 *   backends: ['./backends/elastic']
 *  (if the config file is in the statsd folder)
 *
 * A sample configuration can be found in exampleElasticConfig.js
 *
 * This backend supports the following config options:
 *
 *   host:            hostname or IP of ElasticSearch server
 *   port:            port of Elastic Search Server
 *   path:            http path of Elastic Search Server (default: '/')
 *   indexPrefix:     Prefix of the dynamic index to be created (default: 'statsd')
 *   indexTimestamp:  Timestamping format of the index, either "year", "month" or "day"
 *   indexType:       The dociment type of the saved stat (default: 'stat')
 */

var net = require('net'),
   util = require('util'),
   http = require('http');
// this will be instantiated to the logger
var lg;
var debug;
var flushInterval;
var elasticHost;
var elasticPort;
var elasticPath;
var elasticIndex;
var elasticIndexTimestamp;
var elasticCountType;
var elasticTimerType;

var elasticStats = {};

var es_bulk_insert = function elasticsearch_bulk_insert(listCounters, listTimers, listTimerData, listGaugeData) {

      var indexDate = new Date();

      var statsdIndex = elasticIndex + '-' + indexDate.getUTCFullYear()

      if (elasticIndexTimestamp == 'month' || elasticIndexTimestamp == 'day'){
        var indexMo = indexDate.getUTCMonth() +1;
        if (indexMo < 10) {
            indexMo = '0'+indexMo;
        }
        statsdIndex += '.' + indexMo;
      }

      if (elasticIndexTimestamp == 'day'){
        var indexDt = indexDate.getUTCDate();
        if (indexDt < 10) {
            indexDt = '0'+indexDt;
        }
        statsdIndex += '.' +  indexDt;
      }

      var payload = '';
      for (key in listCounters) {
        payload += '{"index":{"_index":"'+statsdIndex+'","_type":"'+elasticCountType+'"}}'+"\n";
        payload += '{';
        innerPayload = '';
          for (statKey in listCounters[key]){
            if (innerPayload) innerPayload += ',';
            innerPayload += '"'+statKey+'":"'+listCounters[key][statKey]+'"';
          }
        payload += innerPayload +'}'+"\n";
      }
      for (key in listTimers) {
        payload += '{"index":{"_index":"'+statsdIndex+'","_type":"'+elasticTimerType+'"}}'+"\n";
        payload += '{';
        innerPayload = '';
          for (statKey in listTimers[key]){
            if (innerPayload) innerPayload += ',';
            innerPayload += '"'+statKey+'":"'+listTimers[key][statKey]+'"';
          }
        payload += innerPayload +'}'+"\n";
      }
      for (key in listTimerData) {
        payload += '{"index":{"_index":"'+statsdIndex+'","_type":"'+elasticTimerDataType+'"}}'+"\n";
        payload += '{';
        innerPayload = '';
          for (statKey in listTimerData[key]){
            if (innerPayload) innerPayload += ',';
            innerPayload += '"'+statKey+'":"'+listTimerData[key][statKey]+'"';
          }
        payload += innerPayload +'}'+"\n";
      }
      for (key in listGaugeData) {
        payload += '{"index":{"_index":"'+statsdIndex+'","_type":"'+elasticGaugeDataType+'"}}'+"\n";
        payload += '{';
        innerPayload = '';
          for (statKey in listGaugeData[key]){
            if (innerPayload) innerPayload += ',';
            innerPayload += '"'+statKey+'":"'+listGaugeData[key][statKey]+'"';
          }
        payload += innerPayload +'}'+"\n";
      }

      var optionsPost = {
        host: elasticHost,
        port: elasticPort,
        path: elasticPath + statsdIndex + '/' + '/_bulk',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': payload.length
        }
      };

      var req = http.request(optionsPost, function(res) {
          res.on('data', function(d) {
            if (Math.floor(res.statusCode / 100) == 5){
              var errdata = "HTTP " + res.statusCode + ": " + d;
              lg.log('error', errdata);
            }
          });
      }).on('error', function(err) {
          lg.log('error', 'Error with HTTP request, no stats flushed.');
          console.log(err);
      });

      if (debug) {
        lg.log('ES payload:');
        lg.log(payload);
      }
      req.write(payload);
      req.end();
}

var flush_stats = function elastic_flush(ts, metrics) {
  var statString = '';
  var numStats = 0;
  var key;
  var array_counts     = new Array();
  var array_timers     = new Array();
  var array_timer_data = new Array();
  var array_gauges     = new Array();

  ts = ts*1000;
/*
  var gauges = metrics.gauges;
  var pctThreshold = metrics.pctThreshold;
*/

  for (key in metrics.counters) {
    numStats += fm.counters(key, metrics.counters[key], ts, array_counts);
  }

  for (key in metrics.timers) {
    numStats += fm.timers(key, metrics.timers[key], ts, array_timers);
  }

  if (array_timers.length > 0) {
    for (key in metrics.timer_data) {
      fm.timer_data(key, metrics.timer_data[key], ts, array_timer_data);
    }
  }

  for (key in metrics.gauges) {
    numStats += fm.gauges(key, metrics.gauges[key], ts, array_gauges);
  }
  if (debug) {
    lg.log('metrics:');
    lg.log( JSON.stringify(metrics) );
  }

  es_bulk_insert(array_counts, array_timers, array_timer_data, array_gauges);

  if (debug) {
    lg.log("debug", "flushed " + numStats + " stats to ES");
  }
};

var elastic_backend_status = function (writeCb) {
  for (stat in elasticStats) {
    writeCb(null, 'elastic', stat, elasticStats[stat]);
  }
};

exports.init = function elasticsearch_init(startup_time, config, events, logger) {

  debug = config.debug;
  lg = logger;

  var configEs = config.elasticsearch || { };

  elasticHost           = configEs.host           || 'localhost';
  elasticPort           = configEs.port           || 9200;
  elasticPath           = configEs.path           || '/';
  elasticIndex          = configEs.indexPrefix    || 'statsd';
  elasticIndexTimestamp = configEs.indexTimestamp || 'day';
  elasticCountType      = configEs.countType      || 'counter';
  elasticTimerType      = configEs.timerType      || 'timer';
  elasticTimerDataType  = configEs.timerDataType  || elasticTimerType + '_stats';
  elasticGaugeDataType  = configEs.gaugeDataType  || 'gauge';
  elasticFormatter      = configEs.formatter      || 'default_format';

  fm   = require('./' + elasticFormatter + '.js')
  if (debug) {
    lg.log("debug", "loaded formatter " + elasticFormatter);
  }

  if (fm.init) {
    fm.init(configEs);
  }
  flushInterval         = config.flushInterval;

  elasticStats.last_flush = startup_time;
  elasticStats.last_exception = startup_time;

  events.on('flush', flush_stats);
  events.on('status', elastic_backend_status);

  return true;
};

<commit_msg>http request timeout<commit_after>/*
 * Flush stats to ElasticSearch (http://www.elasticsearch.org/)
 *
 * To enable this backend, include 'elastic' in the backends
 * configuration array:
 *
 *   backends: ['./backends/elastic']
 *  (if the config file is in the statsd folder)
 *
 * A sample configuration can be found in exampleElasticConfig.js
 *
 * This backend supports the following config options:
 *
 *   host:            hostname or IP of ElasticSearch server
 *   port:            port of Elastic Search Server
 *   path:            http path of Elastic Search Server (default: '/')
 *   indexPrefix:     Prefix of the dynamic index to be created (default: 'statsd')
 *   indexTimestamp:  Timestamping format of the index, either "year", "month" or "day"
 *   indexType:       The dociment type of the saved stat (default: 'stat')
 */

var net = require('net'),
   util = require('util'),
   http = require('http');
// this will be instantiated to the logger
var lg;
var debug;
var flushInterval;
var elasticHost;
var elasticPort;
var elasticPath;
var elasticIndex;
var elasticIndexTimestamp;
var elasticCountType;
var elasticTimerType;

var elasticStats = {};

var es_bulk_insert = function elasticsearch_bulk_insert(listCounters, listTimers, listTimerData, listGaugeData) {

      var indexDate = new Date();

      var statsdIndex = elasticIndex + '-' + indexDate.getUTCFullYear()

      if (elasticIndexTimestamp == 'month' || elasticIndexTimestamp == 'day'){
        var indexMo = indexDate.getUTCMonth() +1;
        if (indexMo < 10) {
            indexMo = '0'+indexMo;
        }
        statsdIndex += '.' + indexMo;
      }

      if (elasticIndexTimestamp == 'day'){
        var indexDt = indexDate.getUTCDate();
        if (indexDt < 10) {
            indexDt = '0'+indexDt;
        }
        statsdIndex += '.' +  indexDt;
      }

      var payload = '';
      for (key in listCounters) {
        payload += '{"index":{"_index":"'+statsdIndex+'","_type":"'+elasticCountType+'"}}'+"\n";
        payload += '{';
        innerPayload = '';
          for (statKey in listCounters[key]){
            if (innerPayload) innerPayload += ',';
            innerPayload += '"'+statKey+'":"'+listCounters[key][statKey]+'"';
          }
        payload += innerPayload +'}'+"\n";
      }
      for (key in listTimers) {
        payload += '{"index":{"_index":"'+statsdIndex+'","_type":"'+elasticTimerType+'"}}'+"\n";
        payload += '{';
        innerPayload = '';
          for (statKey in listTimers[key]){
            if (innerPayload) innerPayload += ',';
            innerPayload += '"'+statKey+'":"'+listTimers[key][statKey]+'"';
          }
        payload += innerPayload +'}'+"\n";
      }
      for (key in listTimerData) {
        payload += '{"index":{"_index":"'+statsdIndex+'","_type":"'+elasticTimerDataType+'"}}'+"\n";
        payload += '{';
        innerPayload = '';
          for (statKey in listTimerData[key]){
            if (innerPayload) innerPayload += ',';
            innerPayload += '"'+statKey+'":"'+listTimerData[key][statKey]+'"';
          }
        payload += innerPayload +'}'+"\n";
      }
      for (key in listGaugeData) {
        payload += '{"index":{"_index":"'+statsdIndex+'","_type":"'+elasticGaugeDataType+'"}}'+"\n";
        payload += '{';
        innerPayload = '';
          for (statKey in listGaugeData[key]){
            if (innerPayload) innerPayload += ',';
            innerPayload += '"'+statKey+'":"'+listGaugeData[key][statKey]+'"';
          }
        payload += innerPayload +'}'+"\n";
      }

      var optionsPost = {
        host: elasticHost,
        port: elasticPort,
        path: elasticPath + statsdIndex + '/' + '/_bulk',
        method: 'POST',
        timeout: 5000,
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': payload.length
        }
      };

      var req = http.request(optionsPost, function(res) {
          res.on('data', function(d) {
            if (Math.floor(res.statusCode / 100) == 5){
              var errdata = "HTTP " + res.statusCode + ": " + d;
              lg.log('error', errdata);
            }
          });
      }).on('error', function(err) {
          lg.log('error', 'Error with HTTP request, no stats flushed.');
          console.log(err);
      });

      if (debug) {
        lg.log('ES payload:');
        lg.log(payload);
      }
      req.write(payload);
      req.end();
}

var flush_stats = function elastic_flush(ts, metrics) {
  var statString = '';
  var numStats = 0;
  var key;
  var array_counts     = new Array();
  var array_timers     = new Array();
  var array_timer_data = new Array();
  var array_gauges     = new Array();

  ts = ts*1000;
/*
  var gauges = metrics.gauges;
  var pctThreshold = metrics.pctThreshold;
*/

  for (key in metrics.counters) {
    numStats += fm.counters(key, metrics.counters[key], ts, array_counts);
  }

  for (key in metrics.timers) {
    numStats += fm.timers(key, metrics.timers[key], ts, array_timers);
  }

  if (array_timers.length > 0) {
    for (key in metrics.timer_data) {
      fm.timer_data(key, metrics.timer_data[key], ts, array_timer_data);
    }
  }

  for (key in metrics.gauges) {
    numStats += fm.gauges(key, metrics.gauges[key], ts, array_gauges);
  }
  if (debug) {
    lg.log('metrics:');
    lg.log( JSON.stringify(metrics) );
  }

  es_bulk_insert(array_counts, array_timers, array_timer_data, array_gauges);

  if (debug) {
    lg.log("debug", "flushed " + numStats + " stats to ES");
  }
};

var elastic_backend_status = function (writeCb) {
  for (stat in elasticStats) {
    writeCb(null, 'elastic', stat, elasticStats[stat]);
  }
};

exports.init = function elasticsearch_init(startup_time, config, events, logger) {

  debug = config.debug;
  lg = logger;

  var configEs = config.elasticsearch || { };

  elasticHost           = configEs.host           || 'localhost';
  elasticPort           = configEs.port           || 9200;
  elasticPath           = configEs.path           || '/';
  elasticIndex          = configEs.indexPrefix    || 'statsd';
  elasticIndexTimestamp = configEs.indexTimestamp || 'day';
  elasticCountType      = configEs.countType      || 'counter';
  elasticTimerType      = configEs.timerType      || 'timer';
  elasticTimerDataType  = configEs.timerDataType  || elasticTimerType + '_stats';
  elasticGaugeDataType  = configEs.gaugeDataType  || 'gauge';
  elasticFormatter      = configEs.formatter      || 'default_format';

  fm   = require('./' + elasticFormatter + '.js')
  if (debug) {
    lg.log("debug", "loaded formatter " + elasticFormatter);
  }

  if (fm.init) {
    fm.init(configEs);
  }
  flushInterval         = config.flushInterval;

  elasticStats.last_flush = startup_time;
  elasticStats.last_exception = startup_time;

  events.on('flush', flush_stats);
  events.on('status', elastic_backend_status);

  return true;
};

<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('springbootangularhtml5')
        .controller('MainController', MainController);

    /** @ngInject */
    function MainController() {
        var vm = this;

    }
})();
<commit_msg>Add an example call to show URL handling<commit_after>(function () {
    'use strict';

    angular
        .module('springbootangularhtml5')
        .controller('MainController', MainController);

    /** @ngInject */
    function MainController($http, $log) {
        var vm = this;

        vm.callService = function () {
            console.log('yep');
            $http.get('api/service1').then(function (response) {
                vm.result = response;
            }, function (reason) {
                $log.error(reason);
            });
        }
    }
})();
<|endoftext|>