<commit_before>module.exports = {
	"1": {"timer": 1, "value": 35, "name": "castle"},
	"2": {"timer": 1, "value": 25, "name": "keep"},
	"3": {"timer": 1, "value": 10, "name": "tower"},
	"4": {"timer": 1, "value": 5, "name": "camp"},
	"5": {"timer": 0, "value": 0, "name": "temple"},
	"6": {"timer": 0, "value": 0, "name": "hollow"},
	"7": {"timer": 0, "value": 0, "name": "estate"},
	"8": {"timer": 0, "value": 0, "name": "overlook"},
	"9": {"timer": 0, "value": 0, "name": "ascent"}
};
<commit_msg>include id in objective type objects<commit_after>module.exports = {
	"1": {"id": 1, "timer": 1, "value": 35, "name": "castle"},
	"2": {"id": 2, "timer": 1, "value": 25, "name": "keep"},
	"3": {"id": 3, "timer": 1, "value": 10, "name": "tower"},
	"4": {"id": 4, "timer": 1, "value": 5, "name": "camp"},
	"5": {"id": 5, "timer": 0, "value": 0, "name": "temple"},
	"6": {"id": 6, "timer": 0, "value": 0, "name": "hollow"},
	"7": {"id": 7, "timer": 0, "value": 0, "name": "estate"},
	"8": {"id": 8, "timer": 0, "value": 0, "name": "overlook"},
	"9": {"id": 9, "timer": 0, "value": 0, "name": "ascent"}
};
<|endoftext|>


<commit_before>/**
 * @class Oskari.mapframework.bundle.statehandler.event.StateSavedEvent
 *
 * This is used to notify that application state has been saved and any listing should refresh
 */
Oskari.clazz.define(
    'Oskari.mapframework.bundle.statehandler.event.StateSavedEvent',
/**
 * @method create called automatically on construction
 * @static
 * @param {Object} state JSON presentation of application state
 */
    function(name, state) {
    	this._name = name;
    	this._state = state;
    	this._error = false;
}, {
    /** @static @property __name event name */
    __name : "StateSavedEvent",
    getName : function() {
        return this.__name;
    },
    /**
     * @method getViewName
     * @return {String} name of the saved view
     */
    getViewName : function() {
        return this._name;
    },
    /**
     * @method getState
     * @return {Object} JSON presentation of application state
     */
    getState : function() {
        return this._state;
    },
    /**
     * @method isError
     * @return {Boolean} true if state couldn't be saved
     */
    isError : function() {
        return this._state;
    },
    /**
     * @method setError
     * @param {Boolean} true if state couldn't be saved
     */
    setError : function(blnError) {
        return this._error = (blnError == true);
    }
}, {
    /**
     * @property {String[]} protocol array of superclasses as {String}
     * @static
     */
    'protocol' : [ 'Oskari.mapframework.event.Event' ]
});
<commit_msg>[PORTTISK-793] copy/paste fix<commit_after>/**
 * @class Oskari.mapframework.bundle.statehandler.event.StateSavedEvent
 *
 * This is used to notify that application state has been saved and any listing should refresh
 */
Oskari.clazz.define(
    'Oskari.mapframework.bundle.statehandler.event.StateSavedEvent',
/**
 * @method create called automatically on construction
 * @static
 * @param {Object} state JSON presentation of application state
 */
    function(name, state) {
    	this._name = name;
    	this._state = state;
    	this._error = false;
}, {
    /** @static @property __name event name */
    __name : "StateSavedEvent",
    getName : function() {
        return this.__name;
    },
    /**
     * @method getViewName
     * @return {String} name of the saved view
     */
    getViewName : function() {
        return this._name;
    },
    /**
     * @method getState
     * @return {Object} JSON presentation of application state
     */
    getState : function() {
        return this._state;
    },
    /**
     * @method isError
     * @return {Boolean} true if state couldn't be saved
     */
    isError : function() {
        return this._error;
    },
    /**
     * @method setError
     * @param {Boolean} true if state couldn't be saved
     */
    setError : function(blnError) {
        return this._error = (blnError == true);
    }
}, {
    /**
     * @property {String[]} protocol array of superclasses as {String}
     * @static
     */
    'protocol' : [ 'Oskari.mapframework.event.Event' ]
});
<|endoftext|>


<commit_before>/* global describe */
/* global process */

var Discord = require("../");
var client = new Discord.Client();
var colors = require("colors");
var fs = require("fs");

var passes = 0, fails = 0;

function section(s) {
	console.log("\n    " + s.yellow);
}

function pass(msg) {
	console.log("      ✓ ".green + msg);
}

function err(msg) {
	console.log("      ✗ ".red + msg);
	process.exit(1);
}

console.log("Beginning Lib Test".yellow);

section("Logging In");

client.on("ready", () => {
	pass("received ready");

	makeServer();
})

client.login(process.env["ds_email"], process.env["ds_password"]).then(token => {

	if (!token || token.length < 1) {
		err("bad token");
		return;
	}

	pass("valid login token");

}).catch(e => err("error logging in: " + e));

var server, channel, message;

function makeServer() {

	section("Server Creation");
	client.createServer("test", "london").then(srv => {

		if (!srv) {
			err("server not passed");
			return;
		}

		if (srv.name !== "test" || srv.region !== "london") {
			err("invalid server name/region");
			return;
		}

		if (!srv.members.has(client.user)) {
			console.log(srv.members);
			err("client not included in members list");
			return;
		}

		pass("created server");
		pass("valid server name & region");
		pass("client included in server members");

		server = srv;

		makeChannel();

	}).catch(e => {
		err("couldn't create server: " + e);
	});
}

function makeChannel() {
	section("Channel Creation");

	client.createChannel(server, "testchannel", "text").then(chann => {

		if (!chann) {
			err("channel not passed");
			return;
		}

		if (chann.name !== "testchannel" || chann.type !== "text") {
			err("invalid channel name/type");
			return;
		}

		pass("channel created");
		pass("valid channel name & type");

		channel = chann;

		editChannel();

	});
}

function editChannel() {
	section("Channel Manipulation");

	client.setChannelNameAndTopic(channel, "testing", "a testing channel - temporary").then(() => {

		if (channel.name !== "testing" || channel.topic !== "a testing channel - temporary") {
			err("channel not updated");
			return;
		}

		pass("channel name and topic updated");

		sendMsg();

	}).catch(e => {
		err("error editting channel: " + e);
	});
}

function sendMsg() {
	section("Message Creation");

	client.sendMessage(channel, "test message!", { tts: true }).then(msg => {

		if (!msg) {
			err("message not passed");
			return;
		}

		if (msg.content !== "test message!" || !msg.sender.equals(client.user) || !msg.channel.equals(channel)) {
			err("invalid content, sender or channel assigned to message");
			return;
		}

		if (!msg.tts) {
			err("message wasn't TTS on response, even though on request it was");
			return;
		}

		pass("message successfully created");
		pass("correct parameters in message");

		message = msg;

		editMsg();

	}).catch(e => {
		err("error sending message: " + e)
	});
}

function editMsg() {

	section("Message Manipulation");

	client.updateMessage(message, client.user + channel + server).then(msg => {

		if (!msg) {
			err("message not passed back on update");
			return;
		}

		if (msg.content !== client.user.mention() + channel.mention() + server.name) {
			err("message content not what expected");
			return;
		}

		pass("message updated");
		pass("message content was as expected - complex");

		client.deleteMessage(message).then(() => {
			pass("message deleted");
			sendFile();
		}).catch(e => {
			err("error deleting message: " + e)
		});

	}).catch(e => {
		err("error updating message: " + e)
	});

}

function sendFile() {
	section("File Sending & Deletion");

	client.sendFile(channel, "./test/image.png", "image.png").then(file => {

		if (!file) {
			err("file not passed");
			return;
		}

		if (file.attachments.length === 0) {
			err("attachment not added");
			return;
		}

		pass("sent attachment file");

		client.deleteMessage(file).then(() => {
			pass("message deleted");
			deleteAll();
		}).catch(e => {
			err("error deleting message: " + e)
		});

	}).catch(e => {
		err("error sending file: " + e);
	});
}

function deleteAll() {

	section("Clean Up");

	client.deleteChannel(channel).then(() => {

		pass("deleted temporary channel");

		client.leaveServer(server).then(() => {

			pass("deleted temporary server");

			exit();

		}).catch(e => {
			err("error deleting server: " + e);
		});

	}).catch(e => {
		err("error deleting channel: " + e);
	});

}

function exit() {

	section("Exiting");

	client.logout().then(() => {
		pass("logged out");
		done();
	}).catch(e => {
		err("couldn't log out: " + e);
	});

}

function done() {
	section("Report");
	pass("all tests done");
	process.exit(0);
}<commit_msg>Updated test script to test more things<commit_after>/* global describe */
/* global process */

var Discord = require("../");
var client = new Discord.Client();
var colors = require("colors");
var fs = require("fs");

var passes = 0, fails = 0;

function section(s) {
	console.log("\n    " + s.yellow.bold.underline);
}

function pass(msg) {
	console.log("      ✓ ".green + msg.italic);
}

function err(msg) {
	console.log("      ✗ ".red + msg.italic);
	process.exit(1);
}

console.log("Beginning Lib Test".yellow);

section("Logging In");

client.on("ready", () => {
	pass("received ready");

	makeServer();
})

client.login(process.env["ds_email"], process.env["ds_password"]).then(token => {

	if (!token || token.length < 1) {
		err("bad token");
		return;
	}

	pass("valid login token");

}).catch(e => err("error logging in: " + e));

var server, channel, message, role, invserver;

function makeServer() {

	section("Server Creation");
	client.createServer("test", "london").then(srv => {

		if (!srv) {
			err("server not passed");
			return;
		}

		if (srv.name !== "test" || srv.region !== "london") {
			err("invalid server name/region");
			return;
		}

		if (!srv.members.has(client.user)) {
			console.log(srv.members);
			err("client not included in members list");
			return;
		}

		pass("created server");
		pass("valid server name & region");
		pass("client included in server members");

		server = srv;

		makeChannel();

	}).catch(e => {
		err("couldn't create server: " + e);
	});
}

function makeChannel() {
	section("Channel Creation");

	client.createChannel(server, "testchannel", "text").then(chann => {

		if (!chann) {
			err("channel not passed");
			return;
		}

		if (chann.name !== "testchannel" || chann.type !== "text") {
			err("invalid channel name/type");
			return;
		}

		pass("channel created");
		pass("valid channel name & type");

		channel = chann;

		editChannel();

	});
}

function editChannel() {
	section("Channel Manipulation");

	client.setChannelNameAndTopic(channel, "testing", "a testing channel - temporary").then(() => {

		if (channel.name !== "testing" || channel.topic !== "a testing channel - temporary") {
			err("channel not updated");
			return;
		}

		pass("channel name and topic updated");

		sendMsg();

	}).catch(e => {
		err("error editting channel: " + e);
	});
}

function sendMsg() {
	section("Message Creation");

	client.sendMessage(channel, "test message!", { tts: true }).then(msg => {

		if (!msg) {
			err("message not passed");
			return;
		}

		if (msg.content !== "test message!" || !msg.sender.equals(client.user) || !msg.channel.equals(channel)) {
			err("invalid content, sender or channel assigned to message");
			return;
		}

		if (!msg.tts) {
			err("message wasn't TTS on response, even though on request it was");
			return;
		}

		pass("message successfully created");
		pass("correct parameters in message");

		message = msg;

		editMsg();

	}).catch(e => {
		err("error sending message: " + e)
	});
}

function editMsg() {

	section("Message Manipulation");

	client.updateMessage(message, client.user + channel + server).then(msg => {

		if (!msg) {
			err("message not passed back on update");
			return;
		}

		if (msg.content !== client.user.mention() + channel.mention() + server.name) {
			err("message content not what expected");
			return;
		}

		pass("message updated");
		pass("message content was as expected - complex");

		client.deleteMessage(message).then(() => {
			pass("message deleted");
			sendFile();
		}).catch(e => {
			err("error deleting message: " + e)
		});

	}).catch(e => {
		err("error updating message: " + e)
	});

}

function sendFile() {
	section("File Sending & Deletion");

	client.sendFile(channel, "./test/image.png", "image.png").then(file => {

		if (!file) {
			err("file not passed");
			return;
		}

		if (file.attachments.length === 0) {
			err("attachment not added");
			return;
		}

		pass("sent attachment file");

		client.deleteMessage(file).then(() => {
			pass("message deleted");
			roleCreate();
		}).catch(e => {
			err("error deleting message: " + e)
		});

	}).catch(e => {
		err("error sending file: " + e);
	});
}

function roleCreate() {
	section("Role Management");

	client.createRole(server, {
		name: "test role",
		hoist: true,
		color: 0xFF0000,
		permissions: [
			"kickMembers"
		]
	}).then(_role => {

		role = _role;

		pass("created role");

		if (role.name !== "test role" || role.color !== 0xFF0000 || !role.hoist){
			err("bad role name, color or hoist");
			return;
		}

		if (!role.hasPermission("kickMembers")) {
			err("role doesn't have kick members permission");
			return;
		}

		pass("correct role metadata");

		joinInvite();

	}).catch(e => {
		err("error creating role: " + e)
	});
}

function joinInvite() {
	section("Joining Servers");

	client.joinServer(process.env["ds_invite"]).then(srv => {

		invserver = srv;
		pass("passed back server");

		if (srv.name !== "d.j s _ t s" || srv.region !== "london") {
			err("incorrect server name or region");
			return;
		}

		pass("correct server name and region");
		sendPM();

	}).catch(e => {
		err("error joining server: " + e)
	});
}

function sendPM() {
	section("Sending PMs");

	client.sendMessage(invserver.owner, "hello, this is a test!").then(msg => {

		pass("sent PM");

		client.deleteMessage(msg).then(() => {
			pass("deleted PM");
			deleteAll();
		}).catch(e => {
			err("error deleting PM message: " + e);
		});

	}).catch(e => {
		err("error sending a PM: " + e)
	})
}

function deleteAll() {

	section("Clean Up");

	client.deleteChannel(channel).then(() => {

		pass("deleted temporary channel");

		client.leaveServer(server).then(() => {

			pass("deleted temporary server");

			exit();

		}).catch(e => {
			err("error deleting server: " + e);
		});

	}).catch(e => {
		err("error deleting channel: " + e);
	});

}

function exit() {

	section("Exiting");

	client.logout().then(() => {
		pass("logged out");
		done();
	}).catch(e => {
		err("couldn't log out: " + e);
	});

}

function done() {
	section("Report");
	pass("all tests done");
	process.exit(0);
}<|endoftext|>


<commit_before>const compileTemplate = require('../src/index.js');
const source = `<template>
<button></button>
<thirdComp1 :style="computedStyle" :class="cls"></thirdComp1>
</template>`
// <view><text :class="{{true? 'bg-green':''}}" >fafafa</text></view>
// <view><text :class="true? 'bg-green':''" >fafafa</text></view>
//
// let result = compileTemplate(source,'web');
let options = {lang: 'vue',
  buildInComponents: {button: "cml-buildin-button"},
  cmss: {
    rem: true,
    scale: 0.5,
    remOptions: {
    // base on 750px standard.
      rootValue: 75,
      // to leave 1px alone.
      minPixelValue: 1.01
    },
    autoprefixOptions: {
      browsers: ['> 0.1%', 'ios >= 8', 'not ie < 12']
    }
  },
  usingComponents: [{
    tagName: 'thirdComp1',
    refUrl: '/path/to/ref1',
    filePath: 'path/to/real1',
    isNative: true
  }, {
    tagName: 'thirdComp2',
    refUrl: '/path/to/ref2',
    filePath: 'path/to/real2',
    isNative: false
  }]
};
console.log('before-compile', source);
let result_web = compileTemplate(source, 'web', options);
let result_wx = compileTemplate(source, 'wx', options);
let result_baidu = compileTemplate(source, 'wx', options);
let result_alipay = compileTemplate(source, 'alipay', options);
// let result_alipay = compileTemplate(source,'alipay',{lang:'cml'});
// console.log('result_web', result_web)
// console.log('result_wx', result_wx)
console.log('result_alipay', result_alipay)
// console.log('result_baidu', result_baidu)
<commit_msg>wrapAliComponents正则匹配修改<commit_after>const compileTemplate = require('../src/index.js');
const source = `<template>
  <c-page title="carousel">
    <c-header title="carousel"></c-header>
    <carousel class="container" indicator-dots="{{true}}"  current="{{0}}" circular="{{true}}">
      <carousel-item>
        <view  class="carousel-item" style="background-color: #EBDEAA"></view>
      </carousel-item>
      <carousel-item>
        <view class="carousel-item" style="background-color: #E3EDCD"></view>
      </carousel-item>
      <carousel-item>
        <view class="carousel-item" style="background-color: #EAEAEF"></view>
      </carousel-item>
    </carousel>
  </c-page>
</template>`
// <view><text :class="{{true? 'bg-green':''}}" >fafafa</text></view>
// <view><text :class="true? 'bg-green':''" >fafafa</text></view>
//
// let result = compileTemplate(source,'web');
let options = {lang: 'cml',
  buildInComponents: {button: "cml-buildin-button"},
  cmss: {
    rem: true,
    scale: 0.5,
    remOptions: {
    // base on 750px standard.
      rootValue: 75,
      // to leave 1px alone.
      minPixelValue: 1.01
    },
    autoprefixOptions: {
      browsers: ['> 0.1%', 'ios >= 8', 'not ie < 12']
    }
  },
  usingComponents: [{
    tagName: 'thirdComp1',
    refUrl: '/path/to/ref1',
    filePath: 'path/to/real1',
    isNative: true
  }, {
    tagName: 'thirdComp2',
    refUrl: '/path/to/ref2',
    filePath: 'path/to/real2',
    isNative: false
  }]
};
console.log('before-compile', source);
let result_web = compileTemplate(source, 'web', options);
let result_wx = compileTemplate(source, 'wx', options);
let result_baidu = compileTemplate(source, 'wx', options);
let result_alipay = compileTemplate(source, 'alipay', options);
// let result_alipay = compileTemplate(source,'alipay',{lang:'cml'});
// console.log('result_web', result_web)
// console.log('result_wx', result_wx)
console.log('result_alipay', result_alipay)
// console.log('result_baidu', result_baidu)
<|endoftext|>


<commit_before>/*
 * Copyright © 2016 Cask Data, Inc.
 *
 * 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.
 */

angular.module(PKG.name + '.feature.hydratorplusplus')
  .controller('HydratorPlusPlusListController', function($scope, myPipelineApi, $stateParams, GLOBALS, mySettings, $state, myHelpers, myWorkFlowApi, myWorkersApi, MyCDAPDataSource, myAppsApi, myAlertOnValium, myLoadingService) {
    var dataSrc = new MyCDAPDataSource($scope);
    var vm = this;

    vm.pipelineList = [];
    vm.currentPage = 1;
    vm.statusCount = {
      running: 0,
      scheduled: 0,
      suspended: 0,
      draft: 0
    };

    vm.GLOBALS = GLOBALS;

    var realtime = [],
        batch = [];

    var statusMap = {};

    myPipelineApi.list({
      namespace: $stateParams.namespace
    })
      .$promise
      .then(function success(res) {
        vm.pipelineList = res;

        fetchDrafts();

        angular.forEach(vm.pipelineList, function (app) {
          app._stats = {};

          fetchRunsInfo(app);
        });

        fetchStatus();

      });

    function fetchRunsInfo(app) {
      var params = {
        namespace: $state.params.namespace,
        appId: app.id,
        scope: $scope
      };

      var api;

      if (app.artifact.name === GLOBALS.etlBatch || app.artifact.name === GLOBALS.etlDataPipeline) {
        api = myWorkFlowApi;

        var workflowId = app.artifact.name === GLOBALS.etlDataPipeline ? 'DataPipelineWorkflow' : 'ETLWorkflow';
        params.workflowId = workflowId;

        batch.push({
          appId: app.id,
          programType: 'Workflow',
          programId: workflowId
        });
      } else {
        api = myWorkersApi;
        params.workerId = 'ETLWorker';

        realtime.push({
          appId: app.id,
          programType: 'Worker',
          programId: 'ETLWorker'
        });
      }

      api.runs(params)
        .$promise
        .then(function (runs) {
          app._stats.numRuns = runs.length;
          app._stats.lastStartTime = runs.length > 0 ? runs[0].start : 'N/A';

          for (var i = 0; i < runs.length; i++) {
            var status = runs[i].status;

            if (['RUNNING', 'STARTING', 'STOPPING'].indexOf(status) === -1) {
              app._latest = runs[i];
              break;
            }
          }

        });
    }

    function fetchStatus() {
      // fetching ETL Batch statuses
      dataSrc.request({
        _cdapNsPath: '/status',
        method: 'POST',
        body: batch
      })
      .then(function (res) {
        angular.forEach(res, function (app) {
          if (app.status === 'RUNNING') {
            statusMap[app.appId] = 'Running';
            vm.statusCount.running++;
          } else {
            /**
             * FIXME: https://github.com/caskdata/cdap/pull/5426
             * The check for app.programId is because we don't have the artifact name here
             **/
            myWorkFlowApi.getScheduleStatus({
              namespace: $state.params.namespace,
              appId: app.appId,
              scheduleId: app.programId === 'ETLWorkflow' ? 'etlWorkflow' : 'dataPipelineSchedule',
              scope: $scope
            })
              .$promise
              .then(function (schedule) {
                if (schedule.status === 'SCHEDULED') {
                  statusMap[app.appId] = 'Scheduled';
                  vm.statusCount.scheduled++;
                } else {
                  statusMap[app.appId] = 'Suspended';
                  vm.statusCount.suspended++;
                }
                updateStatusAppObject();
              });
          }
        });

        updateStatusAppObject();
      }); // end of ETL Batch

      //fetching ETL Realtime statuses
      dataSrc.request({
        _cdapNsPath: '/status',
        method: 'POST',
        body: realtime
      })
      .then(function (res) {
        angular.forEach(res, function (app) {
          if (app.status === 'RUNNING') {
            statusMap[app.appId] = 'Running';
            vm.statusCount.running++;
          } else {
            statusMap[app.appId] = 'Suspended';
            vm.statusCount.suspended++;
          }
        });

        updateStatusAppObject();
      });

    }

    function updateStatusAppObject() {
      angular.forEach(vm.pipelineList, function (app) {
        app._status = app._status || statusMap[app.id];
      });
    }

    function fetchDrafts() {
      mySettings.get('hydratorDrafts')
        .then(function(res) {
          let draftsList = myHelpers.objectQuery(res, $stateParams.namespace);
          if (!angular.isObject(draftsList)) {
            return;
          }
          if (Object.keys(draftsList).length) {
            angular.forEach(res[$stateParams.namespace], function(value, key) {
              vm.statusCount.draft++;
              vm.pipelineList.push({
                isDraft: true,
                name: value.name,
                id: (value.__ui__  && value.__ui__.draftId) ? value.__ui__.draftId : key,
                artifact: value.artifact,
                description: myHelpers.objectQuery(value, 'description'),
                _status: 'Draft',
                _stats: {
                  numRuns: 'N/A',
                  lastStartTime: 'N/A'
                }
              });
            });
          }
        });
    }

    vm.deleteDraft = function(draftId) {
      myLoadingService.showLoadingIcon()
      .then(function(){
        let draftName;
        mySettings.get('hydratorDrafts')
          .then(function(res){
            let draft = myHelpers.objectQuery(res, $stateParams.namespace, draftId);
            if(draft){
              draftName = draft.name;
              delete res[$stateParams.namespace][draftId];
            }
            return mySettings.set('hydratorDrafts', res);
          })
          .then(
              function success() {
                myLoadingService.hideLoadingIconImmediate();
                $state.reload()
                  .then(function() {
                    myAlertOnValium.show({
                      type: 'success',
                      content: 'Pipeline draft ' + draftName + ' deleted successfully'
                    });
                  });
              },
              function error() {
                myLoadingService.hideLoadingIconImmediate();
                $state.reload()
                  .then(function() {
                    myAlertOnValium.show({
                      type: 'danger',
                      content: 'Pipeline draft ' + draftName + ' delete failed'
                    });
                  });
              });
      });
    };

    vm.deleteApp = function (appId) {
      myLoadingService.showLoadingIcon()
      .then(function(){
        var deleteParams = {
          namespace: $state.params.namespace,
          appId: appId,
          scope: $scope
        };
        return myAppsApi.delete(deleteParams)
          .$promise;
      })
      .then(function success () {
        myLoadingService.hideLoadingIconImmediate();
        $state.reload()
          .then(function() {
            myAlertOnValium.show({
              type: 'success',
              content: 'Pipeline ' + appId + ' deleted successfully'
            });
          });
      }, function error () {
        myLoadingService.hideLoadingIconImmediate();
        $state.reload()
          .then(function() {
            myAlertOnValium.show({
              type: 'danger',
              content:  'Pipeline ' + appId + ' delete failed'
            });
          });
      });
    };
  });
<commit_msg>fix status in list view for data stream<commit_after>/*
 * Copyright © 2016 Cask Data, Inc.
 *
 * 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.
 */

angular.module(PKG.name + '.feature.hydratorplusplus')
  .controller('HydratorPlusPlusListController', function($scope, myPipelineApi, $stateParams, GLOBALS, mySettings, $state, myHelpers, myWorkFlowApi, myWorkersApi, MyCDAPDataSource, myAppsApi, myAlertOnValium, myLoadingService, mySparkApi) {
    var dataSrc = new MyCDAPDataSource($scope);
    var vm = this;

    vm.pipelineList = [];
    vm.currentPage = 1;
    vm.statusCount = {
      running: 0,
      scheduled: 0,
      suspended: 0,
      draft: 0
    };

    vm.GLOBALS = GLOBALS;

    var realtime = [],
        batch = [];

    var statusMap = {};

    myPipelineApi.list({
      namespace: $stateParams.namespace
    })
      .$promise
      .then(function success(res) {
        vm.pipelineList = res;

        fetchDrafts();

        angular.forEach(vm.pipelineList, function (app) {
          app._stats = {};

          fetchRunsInfo(app);
        });

        fetchStatus();

      });

    function fetchRunsInfo(app) {
      var params = {
        namespace: $state.params.namespace,
        appId: app.id,
        scope: $scope
      };

      var api;

      if (app.artifact.name === GLOBALS.etlBatch || app.artifact.name === GLOBALS.etlDataPipeline) {
        api = myWorkFlowApi;

        var workflowId = app.artifact.name === GLOBALS.etlDataPipeline ? 'DataPipelineWorkflow' : 'ETLWorkflow';
        params.workflowId = workflowId;

        batch.push({
          appId: app.id,
          programType: 'Workflow',
          programId: workflowId
        });
      } else if (app.artifact.name === GLOBALS.etlDataStreams) {
        api = mySparkApi;

        realtime.push({
          appId: app.id,
          programType: 'Spark',
          programId: 'DataStreamsSparkStreaming'
        });

      } else {
        api = myWorkersApi;
        params.workerId = 'ETLWorker';

        realtime.push({
          appId: app.id,
          programType: 'Worker',
          programId: 'ETLWorker'
        });
      }

      api.runs(params)
        .$promise
        .then(function (runs) {
          app._stats.numRuns = runs.length;
          app._stats.lastStartTime = runs.length > 0 ? runs[0].start : 'N/A';

          for (var i = 0; i < runs.length; i++) {
            var status = runs[i].status;

            if (['RUNNING', 'STARTING', 'STOPPING'].indexOf(status) === -1) {
              app._latest = runs[i];
              break;
            }
          }

        });
    }

    function fetchStatus() {
      // fetching ETL Batch statuses
      dataSrc.request({
        _cdapNsPath: '/status',
        method: 'POST',
        body: batch
      })
      .then(function (res) {
        angular.forEach(res, function (app) {
          if (app.status === 'RUNNING') {
            statusMap[app.appId] = 'Running';
            vm.statusCount.running++;
          } else {
            /**
             * FIXME: https://github.com/caskdata/cdap/pull/5426
             * The check for app.programId is because we don't have the artifact name here
             **/
            myWorkFlowApi.getScheduleStatus({
              namespace: $state.params.namespace,
              appId: app.appId,
              scheduleId: app.programId === 'ETLWorkflow' ? 'etlWorkflow' : 'dataPipelineSchedule',
              scope: $scope
            })
              .$promise
              .then(function (schedule) {
                if (schedule.status === 'SCHEDULED') {
                  statusMap[app.appId] = 'Scheduled';
                  vm.statusCount.scheduled++;
                } else {
                  statusMap[app.appId] = 'Suspended';
                  vm.statusCount.suspended++;
                }
                updateStatusAppObject();
              });
          }
        });

        updateStatusAppObject();
      }); // end of ETL Batch

      //fetching ETL Realtime statuses
      dataSrc.request({
        _cdapNsPath: '/status',
        method: 'POST',
        body: realtime
      })
      .then(function (res) {
        angular.forEach(res, function (app) {
          if (app.status === 'RUNNING') {
            statusMap[app.appId] = 'Running';
            vm.statusCount.running++;
          } else {
            statusMap[app.appId] = 'Suspended';
            vm.statusCount.suspended++;
          }
        });

        updateStatusAppObject();
      });

    }

    function updateStatusAppObject() {
      angular.forEach(vm.pipelineList, function (app) {
        app._status = app._status || statusMap[app.id];
      });
    }

    function fetchDrafts() {
      mySettings.get('hydratorDrafts')
        .then(function(res) {
          let draftsList = myHelpers.objectQuery(res, $stateParams.namespace);
          if (!angular.isObject(draftsList)) {
            return;
          }
          if (Object.keys(draftsList).length) {
            angular.forEach(res[$stateParams.namespace], function(value, key) {
              vm.statusCount.draft++;
              vm.pipelineList.push({
                isDraft: true,
                name: value.name,
                id: (value.__ui__  && value.__ui__.draftId) ? value.__ui__.draftId : key,
                artifact: value.artifact,
                description: myHelpers.objectQuery(value, 'description'),
                _status: 'Draft',
                _stats: {
                  numRuns: 'N/A',
                  lastStartTime: 'N/A'
                }
              });
            });
          }
        });
    }

    vm.deleteDraft = function(draftId) {
      myLoadingService.showLoadingIcon()
      .then(function(){
        let draftName;
        mySettings.get('hydratorDrafts')
          .then(function(res){
            let draft = myHelpers.objectQuery(res, $stateParams.namespace, draftId);
            if(draft){
              draftName = draft.name;
              delete res[$stateParams.namespace][draftId];
            }
            return mySettings.set('hydratorDrafts', res);
          })
          .then(
              function success() {
                myLoadingService.hideLoadingIconImmediate();
                $state.reload()
                  .then(function() {
                    myAlertOnValium.show({
                      type: 'success',
                      content: 'Pipeline draft ' + draftName + ' deleted successfully'
                    });
                  });
              },
              function error() {
                myLoadingService.hideLoadingIconImmediate();
                $state.reload()
                  .then(function() {
                    myAlertOnValium.show({
                      type: 'danger',
                      content: 'Pipeline draft ' + draftName + ' delete failed'
                    });
                  });
              });
      });
    };

    vm.deleteApp = function (appId) {
      myLoadingService.showLoadingIcon()
      .then(function(){
        var deleteParams = {
          namespace: $state.params.namespace,
          appId: appId,
          scope: $scope
        };
        return myAppsApi.delete(deleteParams)
          .$promise;
      })
      .then(function success () {
        myLoadingService.hideLoadingIconImmediate();
        $state.reload()
          .then(function() {
            myAlertOnValium.show({
              type: 'success',
              content: 'Pipeline ' + appId + ' deleted successfully'
            });
          });
      }, function error () {
        myLoadingService.hideLoadingIconImmediate();
        $state.reload()
          .then(function() {
            myAlertOnValium.show({
              type: 'danger',
              content:  'Pipeline ' + appId + ' delete failed'
            });
          });
      });
    };
  });
<|endoftext|>


<commit_before>/*

To generate tables -directory from original xml:

# Remove non-utf8 characters (e.g. <E6> @ import_maps - table):
iconv -c -f utf-8 -t utf-8 emeku-original.xml > emeku-stripped-utf8.xml

# Remove utf8 control characters:
tr -d '\036\037' < emeku-stripped-utf8.xml > emeku-fixed-stripped-utf8.xml

# Split all tables to separate xml files
mkdir tables
cd tables
awk '/<!-- Table/{ if (f) { print "</docs>" > f; close(f); } f = $3".xml"; print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<docs>" > f }{ if (f) print > f }' ../emeku-fixed-stripped-utf8.xml

*/

var schema = require('../server/schema')
var xml = require('xml-object-stream')
var mongoose = require('mongoose')
var async = require('async')
var path = require('path')
var fs = require('fs')

var dataDir = path.join(__dirname, '../tables/')
var debug = true

var tasks = {
  wipe: wipe,
  base: base,
  wipeActors: wipeActors,
  actors: actors,
  wipeNames: wipeNames,
  names: names
}

var mappings = {
  meku_audiovisualprograms: { table:'meku_audiovisualprograms', fields: { 'id':mapTo('emeku-id'), 'name':asArray, 'deleted':intToBoolean } },
  meku_actors: { table:'meku_actors', fields: { 'id':1, 'name':trim, 'surname':trim, 'deleted':intToBoolean } },
  meku_audiov_meku_actors_c: { table: 'meku_audiov_meku_actors_c', fields: { 'meku_audio7d9crograms_ida':1, 'meku_audio8fcb_actors_idb':1, 'deleted':intToBoolean } },

  meku_names: { table: 'meku_names', fields: { 'id':1, 'name':trim, 'deleted':intToBoolean } },
  meku_audiovs_meku_names_c: { table: 'meku_audiovs_meku_names_c', fields: { type:1, 'meku_audio91farograms_ida':1, 'meku_audio7e24u_names_idb':1, 'deleted':intToBoolean } }
}

if (process.argv.length < 3) {
  console.error('Usage: node '+process.argv[1]+' [tasks]')
  console.error('  where tasks in: '+Object.keys(tasks).join(', '))
  process.exit(1)
}

mongoose.connect('mongodb://localhost/meku')

var jobs = process.argv.slice(2)

async.eachSeries(jobs, run, function(err) {
  mongoose.disconnect(function() {
    console.log('Done ', err ? err : 'OK')
  })
})

function run(job, callback) {
  console.log('> '+job)
  tasks[job](function(err) {
    console.log('> '+job+' done.', (err ? err : 'OK'))
    callback(err)
  })
}

function wipe(callback) {
  var collections = ['Movie', 'ProductionCompany', 'Account']
  async.each(collections, function(c,callback) { schema[c].remove({}, callback) }, callback)
}

function wipeActors(callback) {
  schema.Movie.update({}, { actors:[] }, { multi:true }, callback)
}

function wipeNames(callback) {
  schema.Movie.update({}, { $push: { name: { $each: [ ], $slice: 1 } } }, { multi:true}, function() {
    schema.Movie.update({}, { 'name-fi': [], 'name-sv': [] }, { multi:true }, callback)
  })
}

function base(callback) {
  parseTableToJsonArray(mappings.meku_audiovisualprograms, function(err, programs) {
    if (err) return callback(err)
    massCreate('Movie', programs, callback)
  })
}

function names(callback) {
  // NOTE: This has NOT been tested yet.
  parseTableToJsonArray(mappings.meku_names, function(err, allNames) {
    if (err) return callback(err)
    parseTableToJsonArray(mappings.meku_audiovs_meku_names_c, function(err, allLinks) {
      if (err) return callback(err)
      var nameMap = toIdObject('id', allNames)
      console.log('> mapping names')
      var updates = allLinks.map(function(link) {
        var type = movieNameType(link.type)
        if (!type) return undefined
        var name = nameMap[link.meku_audio7e24u_names_idb]
        if (!name) return undefined
        return {
          cond: { 'emeku-id': link.meku_audio91farograms_ida },
          update: { $addToSet: keyValue(type, name.name) }
        }
      }).filter(function(u) { return u !== undefined })
      console.log('> updating names')
      massUpdate('Movie', updates, callback)
    })
  })

  function movieNameType(type) {
    if (type == '1A') return 'name'
    if (type == '2S') return 'name-fi'
    if (type == '3R') return 'name-sv'
    return undefined
  }
}

function actors(callback) {
  parseTableToJsonArray(mappings.meku_actors, function(err, allActors) {
    if (err) return callback(err)
    parseTableToJsonArray(mappings.meku_audiov_meku_actors_c, function(err, allLinks) {
      if (err) return callback(err)
      console.log('> idfying actors')
      var actorMap = toIdObject('id', allActors)
      console.log('> mapping actors')
      var updates = allLinks.map(function(link) {
        var actor = actorMap[link.meku_audio8fcb_actors_idb]
        if (!actor) return undefined
        return {
          cond: { 'emeku-id': link.meku_audio7d9crograms_ida },
          update: { $addToSet: { actors: ((actor.name || '') + ' ' + (actor.surname || '')).trim() } }
        }
      }).filter(function(u) { return u !== undefined })
      console.log('> updating actors')
      massUpdate('Movie', updates, callback)
    })
  })
}

function massCreate(schemaName, objects, callback) {
  async.eachLimit(objects, 5, function(obj, callback) { schema[schemaName].create(obj, callback) }, callback)
}
function massUpdate(schemaName, objects, callback) {
  async.eachLimit(objects, 5, function(obj, callback) { schema[schemaName].update(obj.cond, obj.update, {}, callback) }, callback)
}

function toIdObject(idKey, array) {
  var result = {}
  array.forEach(function(item) { result[item[idKey]] = item })
  return result
}

function parseTableToJsonArray(mapping, callback) {
  var ii = 0
  var result = []
  var parser = xml.parse(fs.createReadStream(path.join(dataDir, mapping.table+'.xml')))

  if (debug) process.stdout.write('\n'+mapping.table)
  parser.each('table', function(table) {
    if (debug && ((ii++) % 500 == 0)) process.stdout.write('.')
    result.push(toObject(table, mapping.fields))
  })
  parser.on('error', callback)
  parser.on('end', function() { callback(null, result) })

  // TODO: do we need to explicitly close the read stream?
}

function toObject(table, fieldMapping) {
  var obj = {}
  table.$children.forEach(function(c) {
    var columnName = c.$.name
    var value = c.$text
    if (value == 'NULL') return
    var mapper = fieldMapping[columnName]
    if (mapper) {
      if (mapper == '1') {
        obj[columnName] = value
      } else {
        mapper(obj, columnName, value)
      }
    }
  })
  return obj
}

function asArray(obj, key, value) {
  obj[key] = [(value || '').trim()]
}

function mapTo(fieldName) {
  return function(obj, key, value) {
    obj[fieldName] = value
  }
}
function trim(obj, key, value) {
  obj[key] = (value || '').trim()
}
function intToBoolean(obj, value) {
  if (value == '1') obj[key] = true
}

function keyValue(key, value) {
  var o = {}
  o[key] = value
  return o
}<commit_msg>Add warning about work in progress.<commit_after>/*

To generate tables -directory from original xml:

# Remove non-utf8 characters (e.g. <E6> @ import_maps - table):
iconv -c -f utf-8 -t utf-8 emeku-original.xml > emeku-stripped-utf8.xml

# Remove utf8 control characters:
tr -d '\036\037' < emeku-stripped-utf8.xml > emeku-fixed-stripped-utf8.xml

# Split all tables to separate xml files
mkdir tables
cd tables
awk '/<!-- Table/{ if (f) { print "</docs>" > f; close(f); } f = $3".xml"; print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<docs>" > f }{ if (f) print > f }' ../emeku-fixed-stripped-utf8.xml

*/

// TODO: None of the import functions currently handle the deleted-attribute!

var schema = require('../server/schema')
var xml = require('xml-object-stream')
var mongoose = require('mongoose')
var async = require('async')
var path = require('path')
var fs = require('fs')

var dataDir = path.join(__dirname, '../tables/')
var debug = true

var tasks = {
  wipe: wipe,
  base: base,
  wipeActors: wipeActors,
  actors: actors,
  wipeNames: wipeNames,
  names: names
}

var mappings = {
  meku_audiovisualprograms: { table:'meku_audiovisualprograms', fields: { 'id':mapTo('emeku-id'), 'name':asArray, 'deleted':intToBoolean } },
  meku_actors: { table:'meku_actors', fields: { 'id':1, 'name':trim, 'surname':trim, 'deleted':intToBoolean } },
  meku_audiov_meku_actors_c: { table: 'meku_audiov_meku_actors_c', fields: { 'meku_audio7d9crograms_ida':1, 'meku_audio8fcb_actors_idb':1, 'deleted':intToBoolean } },

  meku_names: { table: 'meku_names', fields: { 'id':1, 'name':trim, 'deleted':intToBoolean } },
  meku_audiovs_meku_names_c: { table: 'meku_audiovs_meku_names_c', fields: { type:1, 'meku_audio91farograms_ida':1, 'meku_audio7e24u_names_idb':1, 'deleted':intToBoolean } }
}

if (process.argv.length < 3) {
  console.error('Usage: node '+process.argv[1]+' [tasks]')
  console.error('  where tasks in: '+Object.keys(tasks).join(', '))
  process.exit(1)
}

mongoose.connect('mongodb://localhost/meku')

var jobs = process.argv.slice(2)

async.eachSeries(jobs, run, function(err) {
  mongoose.disconnect(function() {
    console.log('Done ', err ? err : 'OK')
  })
})

function run(job, callback) {
  console.log('> '+job)
  tasks[job](function(err) {
    console.log('> '+job+' done.', (err ? err : 'OK'))
    callback(err)
  })
}

function wipe(callback) {
  var collections = ['Movie', 'ProductionCompany', 'Account']
  async.each(collections, function(c,callback) { schema[c].remove({}, callback) }, callback)
}

function wipeActors(callback) {
  schema.Movie.update({}, { actors:[] }, { multi:true }, callback)
}

function wipeNames(callback) {
  schema.Movie.update({}, { $push: { name: { $each: [ ], $slice: 1 } } }, { multi:true}, function() {
    schema.Movie.update({}, { 'name-fi': [], 'name-sv': [] }, { multi:true }, callback)
  })
}

function base(callback) {
  parseTableToJsonArray(mappings.meku_audiovisualprograms, function(err, programs) {
    if (err) return callback(err)
    massCreate('Movie', programs, callback)
  })
}

function names(callback) {
  // NOTE: This has NOT been tested yet.
  parseTableToJsonArray(mappings.meku_names, function(err, allNames) {
    if (err) return callback(err)
    parseTableToJsonArray(mappings.meku_audiovs_meku_names_c, function(err, allLinks) {
      if (err) return callback(err)
      var nameMap = toIdObject('id', allNames)
      console.log('> mapping names')
      var updates = allLinks.map(function(link) {
        var type = movieNameType(link.type)
        if (!type) return undefined
        var name = nameMap[link.meku_audio7e24u_names_idb]
        if (!name) return undefined
        return {
          cond: { 'emeku-id': link.meku_audio91farograms_ida },
          update: { $addToSet: keyValue(type, name.name) }
        }
      }).filter(function(u) { return u !== undefined })
      console.log('> updating names')
      massUpdate('Movie', updates, callback)
    })
  })

  function movieNameType(type) {
    if (type == '1A') return 'name'
    if (type == '2S') return 'name-fi'
    if (type == '3R') return 'name-sv'
    return undefined
  }
}

function actors(callback) {
  parseTableToJsonArray(mappings.meku_actors, function(err, allActors) {
    if (err) return callback(err)
    parseTableToJsonArray(mappings.meku_audiov_meku_actors_c, function(err, allLinks) {
      if (err) return callback(err)
      console.log('> idfying actors')
      var actorMap = toIdObject('id', allActors)
      console.log('> mapping actors')
      var updates = allLinks.map(function(link) {
        var actor = actorMap[link.meku_audio8fcb_actors_idb]
        if (!actor) return undefined
        return {
          cond: { 'emeku-id': link.meku_audio7d9crograms_ida },
          update: { $addToSet: { actors: ((actor.name || '') + ' ' + (actor.surname || '')).trim() } }
        }
      }).filter(function(u) { return u !== undefined })
      console.log('> updating actors')
      massUpdate('Movie', updates, callback)
    })
  })
}

function massCreate(schemaName, objects, callback) {
  async.eachLimit(objects, 5, function(obj, callback) { schema[schemaName].create(obj, callback) }, callback)
}
function massUpdate(schemaName, objects, callback) {
  async.eachLimit(objects, 5, function(obj, callback) { schema[schemaName].update(obj.cond, obj.update, {}, callback) }, callback)
}

function toIdObject(idKey, array) {
  var result = {}
  array.forEach(function(item) { result[item[idKey]] = item })
  return result
}

function parseTableToJsonArray(mapping, callback) {
  var ii = 0
  var result = []
  var parser = xml.parse(fs.createReadStream(path.join(dataDir, mapping.table+'.xml')))

  if (debug) process.stdout.write('\n'+mapping.table)
  parser.each('table', function(table) {
    if (debug && ((ii++) % 500 == 0)) process.stdout.write('.')
    result.push(toObject(table, mapping.fields))
  })
  parser.on('error', callback)
  parser.on('end', function() { callback(null, result) })

  // TODO: do we need to explicitly close the read stream?
}

function toObject(table, fieldMapping) {
  var obj = {}
  table.$children.forEach(function(c) {
    var columnName = c.$.name
    var value = c.$text
    if (value == 'NULL') return
    var mapper = fieldMapping[columnName]
    if (mapper) {
      if (mapper == '1') {
        obj[columnName] = value
      } else {
        mapper(obj, columnName, value)
      }
    }
  })
  return obj
}

function asArray(obj, key, value) {
  obj[key] = [(value || '').trim()]
}

function mapTo(fieldName) {
  return function(obj, key, value) {
    obj[fieldName] = value
  }
}
function trim(obj, key, value) {
  obj[key] = (value || '').trim()
}
function intToBoolean(obj, value) {
  if (value == '1') obj[key] = true
}

function keyValue(key, value) {
  var o = {}
  o[key] = value
  return o
}<|endoftext|>


<commit_before>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
var Joi = require('joi');

var appDeployValidator = module.exports = {};

appDeployValidator.get = {
    options : { flatten : true },
    params: {
        projectId: Joi.string().max(40).required()
    }
};
appDeployValidator.serverList = {
    options : { flatten : true },
    params: {
        nexusId: Joi.string().max(40).required(),
        projectId: Joi.string().max(40).required()
    }
};
appDeployValidator.artifactList = {
    options : { flatten : true },
    params: {
        nexusId: Joi.string().max(40).required(),
        repoName: Joi.string().max(20).required(),
        groupId: Joi.string().max(30).required()
    }
};

appDeployValidator.versionList = {
    options : { flatten : true },
    params: {
        nexusId: Joi.string().max(40).required(),
        repoName: Joi.string().max(20).required(),
        groupId: Joi.string().max(30).required(),
        artifactId: Joi.string().max(40).required()
    }
};

appDeployValidator.appDeployHistoryList = {
    options : { flatten : true },
    params: {
        projectId: Joi.string().max(40).required(),
        envName: Joi.string().max(20).required(),
        version: Joi.string().max(20).required(),
        appName: Joi.string().max(30).required()
    }
};

appDeployValidator.post={
    options : { flatten : true },
    body: {
        projectId: Joi.string().min(1).max(40).required(),
        envId:     Joi.array().max(10).required(),
        envSequence:  Joi.array().max(10).required()
    }
};

appDeployValidator.getDeployPermission={
    options : { flatten : true },
    params: {
            projectId: Joi.string().min(1).max(40).required(),
            envName:     Joi.string().max(10).required(),
            appName:  Joi.string().max(40).required()
    }
};

appDeployValidator.deployPermission={
    options : { flatten : true },
    body: {
        projectId: Joi.string().min(1).max(40).required(),
        envName:   Joi.string().max(10).required(),
        appName:  Joi.string().max(40).required(),
        version:  Joi.string().max(40).required(),
        comments: Joi.string().max(100),
        isApproved: Joi.boolean().required()
    }
};

<commit_msg>Add RowId field for App Data(Nexus and Dcoker) and change config response<commit_after>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
var Joi = require('joi');

var appDeployValidator = module.exports = {};

appDeployValidator.get = {
    options : { flatten : true },
    params: {
        projectId: Joi.string().max(40).required()
    }
};
appDeployValidator.serverList = {
    options : { flatten : true },
    params: {
        nexusId: Joi.string().max(40).required(),
        projectId: Joi.string().max(40).required()
    }
};
appDeployValidator.artifactList = {
    options : { flatten : true },
    params: {
        nexusId: Joi.string().max(40).required(),
        repoName: Joi.string().max(20).required(),
        groupId: Joi.string().max(30).required()
    }
};

appDeployValidator.versionList = {
    options : { flatten : true },
    params: {
        nexusId: Joi.string().max(40).required(),
        repoName: Joi.string().max(20).required(),
        groupId: Joi.string().max(30).required(),
        artifactId: Joi.string().max(40).required()
    }
};

appDeployValidator.appDeployHistoryList = {
    options : { flatten : true },
    params: {
        projectId: Joi.string().max(40).required(),
        envName: Joi.string().max(20).required(),
        version: Joi.string().max(20).required(),
        appName: Joi.string().max(30).required()
    }
};

appDeployValidator.post={
    options : { flatten : true },
    body: {
        projectId: Joi.string().min(1).max(40).required(),
        envId:     Joi.array().max(20).required(),
        envSequence:  Joi.array().max(20).required()
    }
};

appDeployValidator.getDeployPermission={
    options : { flatten : true },
    params: {
            projectId: Joi.string().min(1).max(40).required(),
            envName:     Joi.string().max(10).required(),
            appName:  Joi.string().max(40).required()
    }
};

appDeployValidator.deployPermission={
    options : { flatten : true },
    body: {
        projectId: Joi.string().min(1).max(40).required(),
        envName:   Joi.string().max(10).required(),
        appName:  Joi.string().max(40).required(),
        version:  Joi.string().max(40).required(),
        comments: Joi.string().max(100),
        isApproved: Joi.boolean().required()
    }
};

<|endoftext|>


<commit_before>beforeEach(function() {

  function cssMatcher(presentClasses, absentClasses) {
    return function() {
      var element = angular.element(this.actual);
      var present = true;
      var absent = false;

      angular.forEach(presentClasses.split(' '), function(className){
        present = present && element.hasClass(className);
      });

      angular.forEach(absentClasses.split(' '), function(className){
        absent = absent || element.hasClass(className);
      });

      this.message = function() {
        return "Expected to have " + presentClasses +
          (absentClasses ? (" and not have " + absentClasses + "" ) : "") +
          " but had " + element[0].className + ".";
      };
      return present && !absent;
    };
  }

  function indexOf(array, obj) {
    for ( var i = 0; i < array.length; i++) {
      if (obj === array[i]) return i;
    }
    return -1;
  }

  this.addMatchers({
    toBeInvalid: cssMatcher('ng-invalid', 'ng-valid'),
    toBeValid: cssMatcher('ng-valid', 'ng-invalid'),
    toBeDirty: cssMatcher('ng-dirty', 'ng-pristine'),
    toBePristine: cssMatcher('ng-pristine', 'ng-dirty'),

    toEqual: function(expected) {
      if (this.actual && this.actual.$$log) {
        this.actual = (typeof expected === 'string')
            ? this.actual.toString()
            : this.actual.toArray();
      }
      return jasmine.Matchers.prototype.toEqual.call(this, expected);
    },

    toEqualData: function(expected) {
      return angular.equals(this.actual, expected);
    },

    toEqualError: function(message) {
      this.message = function() {
        var expected;
        if (this.actual.message && this.actual.name == 'Error') {
          expected = toJson(this.actual.message);
        } else {
          expected = toJson(this.actual);
        }
        return "Expected " + expected + " to be an Error with message " + toJson(message);
      };
      return this.actual.name == 'Error' && this.actual.message == message;
    },

    toMatchError: function(messageRegexp) {
      this.message = function() {
        var expected;
        if (this.actual.message && this.actual.name == 'Error') {
          expected = angular.toJson(this.actual.message);
        } else {
          expected = angular.toJson(this.actual);
        }
        return "Expected " + expected + " to match an Error with message " + angular.toJson(messageRegexp);
      };
      return this.actual.name == 'Error' && messageRegexp.test(this.actual.message);
    },

    toHaveBeenCalledOnce: function() {
      if (arguments.length > 0) {
        throw new Error('toHaveBeenCalledOnce does not take arguments, use toHaveBeenCalledWith');
      }

      if (!jasmine.isSpy(this.actual)) {
        throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
      }

      this.message = function() {
        var msg = 'Expected spy ' + this.actual.identity + ' to have been called once, but was ',
            count = this.actual.callCount;
        return [
          count === 0 ? msg + 'never called.' :
                        msg + 'called ' + count + ' times.',
          msg.replace('to have', 'not to have') + 'called once.'
        ];
      };

      return this.actual.callCount == 1;
    },

    toHaveBeenCalledOnceWith: function() {
      var expectedArgs = jasmine.util.argsToArray(arguments);

      if (!jasmine.isSpy(this.actual)) {
        throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
      }

      this.message = function() {
        if (this.actual.callCount != 1) {
          if (this.actual.callCount == 0) {
            return [
              'Expected spy ' + this.actual.identity + ' to have been called once with ' +
                jasmine.pp(expectedArgs) + ' but it was never called.',
              'Expected spy ' + this.actual.identity + ' not to have been called with ' +
                jasmine.pp(expectedArgs) + ' but it was.'
            ];
          }

          return [
            'Expected spy ' + this.actual.identity + ' to have been called once with ' +
              jasmine.pp(expectedArgs) + ' but it was called ' + this.actual.callCount + ' times.',
            'Expected spy ' + this.actual.identity + ' not to have been called once with ' +
              jasmine.pp(expectedArgs) + ' but it was.'
          ];
        } else {
          return [
            'Expected spy ' + this.actual.identity + ' to have been called once with ' +
              jasmine.pp(expectedArgs) + ' but was called with ' + jasmine.pp(this.actual.argsForCall),
            'Expected spy ' + this.actual.identity + ' not to have been called once with ' +
              jasmine.pp(expectedArgs) + ' but was called with ' + jasmine.pp(this.actual.argsForCall)
          ];
        }
      };

      return this.actual.callCount === 1 && this.env.contains_(this.actual.argsForCall, expectedArgs);
    },

    toBeOneOf: function() {
      return indexOf(arguments, this.actual) !== -1;
    },

    toHaveClass: function(clazz) {
      this.message = function() {
        return "Expected '" + angular.mock.dump(this.actual) + "' to have class '" + clazz + "'.";
      };
      return this.actual.hasClass ?
              this.actual.hasClass(clazz) :
              angular.element(this.actual).hasClass(clazz);
    }

  });
});
<commit_msg>test(matchers): update toThrow matcher<commit_after>beforeEach(function() {

  function cssMatcher(presentClasses, absentClasses) {
    return function() {
      var element = angular.element(this.actual);
      var present = true;
      var absent = false;

      angular.forEach(presentClasses.split(' '), function(className){
        present = present && element.hasClass(className);
      });

      angular.forEach(absentClasses.split(' '), function(className){
        absent = absent || element.hasClass(className);
      });

      this.message = function() {
        return "Expected to have " + presentClasses +
          (absentClasses ? (" and not have " + absentClasses + "" ) : "") +
          " but had " + element[0].className + ".";
      };
      return present && !absent;
    };
  }

  function indexOf(array, obj) {
    for ( var i = 0; i < array.length; i++) {
      if (obj === array[i]) return i;
    }
    return -1;
  }

  this.addMatchers({
    toBeInvalid: cssMatcher('ng-invalid', 'ng-valid'),
    toBeValid: cssMatcher('ng-valid', 'ng-invalid'),
    toBeDirty: cssMatcher('ng-dirty', 'ng-pristine'),
    toBePristine: cssMatcher('ng-pristine', 'ng-dirty'),

    toEqual: function(expected) {
      if (this.actual && this.actual.$$log) {
        this.actual = (typeof expected === 'string')
            ? this.actual.toString()
            : this.actual.toArray();
      }
      return jasmine.Matchers.prototype.toEqual.call(this, expected);
    },

    toEqualData: function(expected) {
      return angular.equals(this.actual, expected);
    },

    toEqualError: function(message) {
      this.message = function() {
        var expected;
        if (this.actual.message && this.actual.name == 'Error') {
          expected = toJson(this.actual.message);
        } else {
          expected = toJson(this.actual);
        }
        return "Expected " + expected + " to be an Error with message " + toJson(message);
      };
      return this.actual.name == 'Error' && this.actual.message == message;
    },

    toMatchError: function(messageRegexp) {
      this.message = function() {
        var expected;
        if (this.actual.message && this.actual.name == 'Error') {
          expected = angular.toJson(this.actual.message);
        } else {
          expected = angular.toJson(this.actual);
        }
        return "Expected " + expected + " to match an Error with message " + angular.toJson(messageRegexp);
      };
      return this.actual.name == 'Error' && messageRegexp.test(this.actual.message);
    },

    toHaveBeenCalledOnce: function() {
      if (arguments.length > 0) {
        throw new Error('toHaveBeenCalledOnce does not take arguments, use toHaveBeenCalledWith');
      }

      if (!jasmine.isSpy(this.actual)) {
        throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
      }

      this.message = function() {
        var msg = 'Expected spy ' + this.actual.identity + ' to have been called once, but was ',
            count = this.actual.callCount;
        return [
          count === 0 ? msg + 'never called.' :
                        msg + 'called ' + count + ' times.',
          msg.replace('to have', 'not to have') + 'called once.'
        ];
      };

      return this.actual.callCount == 1;
    },

    toHaveBeenCalledOnceWith: function() {
      var expectedArgs = jasmine.util.argsToArray(arguments);

      if (!jasmine.isSpy(this.actual)) {
        throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
      }

      this.message = function() {
        if (this.actual.callCount != 1) {
          if (this.actual.callCount == 0) {
            return [
              'Expected spy ' + this.actual.identity + ' to have been called once with ' +
                jasmine.pp(expectedArgs) + ' but it was never called.',
              'Expected spy ' + this.actual.identity + ' not to have been called with ' +
                jasmine.pp(expectedArgs) + ' but it was.'
            ];
          }

          return [
            'Expected spy ' + this.actual.identity + ' to have been called once with ' +
              jasmine.pp(expectedArgs) + ' but it was called ' + this.actual.callCount + ' times.',
            'Expected spy ' + this.actual.identity + ' not to have been called once with ' +
              jasmine.pp(expectedArgs) + ' but it was.'
          ];
        } else {
          return [
            'Expected spy ' + this.actual.identity + ' to have been called once with ' +
              jasmine.pp(expectedArgs) + ' but was called with ' + jasmine.pp(this.actual.argsForCall),
            'Expected spy ' + this.actual.identity + ' not to have been called once with ' +
              jasmine.pp(expectedArgs) + ' but was called with ' + jasmine.pp(this.actual.argsForCall)
          ];
        }
      };

      return this.actual.callCount === 1 && this.env.contains_(this.actual.argsForCall, expectedArgs);
    },

    toBeOneOf: function() {
      return indexOf(arguments, this.actual) !== -1;
    },

    toHaveClass: function(clazz) {
      this.message = function() {
        return "Expected '" + angular.mock.dump(this.actual) + "' to have class '" + clazz + "'.";
      };
      return this.actual.hasClass ?
              this.actual.hasClass(clazz) :
              angular.element(this.actual).hasClass(clazz);
    }

  });
});

// TODO(vojta): remove this once Jasmine in Karma gets updated
// https://github.com/pivotal/jasmine/blob/c40b64a24c607596fa7488f2a0ddb98d063c872a/src/core/Matchers.js#L217-L246
// This toThrow supports RegExps.
jasmine.Matchers.prototype.toThrow = function(expected) {
  var result = false;
  var exception, exceptionMessage;
  if (typeof this.actual != 'function') {
    throw new Error('Actual is not a function');
  }
  try {
    this.actual();
  } catch (e) {
    exception = e;
  }

  if (exception) {
    exceptionMessage = exception.message || exception;
    result = (isUndefined(expected) || this.env.equals_(exceptionMessage, expected.message || expected) || (jasmine.isA_("RegExp", expected) && expected.test(exceptionMessage)));
  }

  var not = this.isNot ? "not " : "";
  var regexMatch = jasmine.isA_("RegExp", expected) ? " an exception matching" : "";

  this.message = function() {
    if (exception) {
      return ["Expected function " + not + "to throw" + regexMatch, expected ? expected.message || expected : "an exception", ", but it threw", exceptionMessage].join(' ');
    } else {
      return "Expected function to throw an exception.";
    }
  };

  return result;
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var _ = require('lodash');

function requiredProcessEnv(name) {
  if (!process.env[name]) {
    throw new Error('You must set the ' + name + ' environment variable');
  }
  return process.env[name];
}

// All configurations will extend these options
// ============================================
var all = {
  env: process.env.NODE_ENV,

  // Root path of server
  root: path.normalize(__dirname + '/../../..'),

  // Server port
  port: process.env.PORT || 9000,

  stateFile: 'state.json',

  db: {
    user: '',
    password: ''
  },

  poisk: {
    enabled: false,
    apiEndpoint: '... some endpoint ...',
    pollInterval: 5 * 60 * 1000 // in ms; how often is the poisk service called?
  },

  spaceDevices: {
    clearEntriesAfter: 30 * 60 * 1000, // after this time in ms, all entries will be cleared
    dbUpdateTime: 15 * 60 * 1000, // after this time in ms, we update the state into the db (if changed)
    list: [
      {
        name: 'I am shy',
        mode: 'hidden',
        devices: [ 'abc', '123' ]
      },
      {
        name: 'Show Me',
        // the id in our open id server ( id.kreativitaet-trifft-technik.de ). Optional.
        id: 'someUser',
        mode: 'visible',
        devices: [ 'foo', 'bar']
      },
      {
        name: 'internal devices',
        mode: 'ignore',
        devices: ['1', '2', '3']
      }
    ]
  },

  twitter: {
    mocking: false, // if true, it does everthing except the actual tweet. Useful for developing.
    enabled: false,
    twitterdelay: 3 * 60 * 1000, // delay tweeting after space state change for this long; it's also the minimum time between two tweets
    tweetClosingState: true, // if true, a closing tweet will be sent
    // twitter auth
    auth: {
      consumer_key: '',
      consumer_secret: '',
      access_token_key: '',
      access_token_secret: ''
    }
  },

  xmpp: {
    enabled: false,
    client: {
      jid: '',
      password: '',
      host: '',
      port: 5222,
      reconnect: true
    }
  },

  app: {
    psk: '',
    port: 7996,
    behindProxy: false,
    logIp: false,
    'listenersmininterval': 200, // Update listener counts on stream at most every X milliseconds
    'streamkeepaliveinterval': 60 * 60 * 1000, // Send a keepalive event this often
    // save the current state this often (in addition to on shutdown)
    'saveinterval': 5 * 60 * 1000
  }

};

// Export the config object based on the NODE_ENV
// ==============================================
module.exports = _.merge(
  all,
    require('./' + process.env.NODE_ENV + '.js') || {});<commit_msg>host and database settings<commit_after>'use strict';

var path = require('path');
var _ = require('lodash');

function requiredProcessEnv(name) {
  if (!process.env[name]) {
    throw new Error('You must set the ' + name + ' environment variable');
  }
  return process.env[name];
}

// All configurations will extend these options
// ============================================
var all = {
  env: process.env.NODE_ENV,

  // Root path of server
  root: path.normalize(__dirname + '/../../..'),

  // Server port
  port: process.env.PORT || 9000,

  stateFile: 'state.json',

  db: {
    host: '',
    database: '',
    user: '',
    password: ''
  },

  poisk: {
    enabled: false,
    apiEndpoint: '... some endpoint ...',
    pollInterval: 5 * 60 * 1000 // in ms; how often is the poisk service called?
  },

  spaceDevices: {
    clearEntriesAfter: 30 * 60 * 1000, // after this time in ms, all entries will be cleared
    dbUpdateTime: 15 * 60 * 1000, // after this time in ms, we update the state into the db (if changed)
    list: [
      {
        name: 'I am shy',
        mode: 'hidden',
        devices: [ 'abc', '123' ]
      },
      {
        name: 'Show Me',
        // the id in our open id server ( id.kreativitaet-trifft-technik.de ). Optional.
        id: 'someUser',
        mode: 'visible',
        devices: [ 'foo', 'bar']
      },
      {
        name: 'internal devices',
        mode: 'ignore',
        devices: ['1', '2', '3']
      }
    ]
  },

  twitter: {
    mocking: false, // if true, it does everthing except the actual tweet. Useful for developing.
    enabled: false,
    twitterdelay: 3 * 60 * 1000, // delay tweeting after space state change for this long; it's also the minimum time between two tweets
    tweetClosingState: true, // if true, a closing tweet will be sent
    // twitter auth
    auth: {
      consumer_key: '',
      consumer_secret: '',
      access_token_key: '',
      access_token_secret: ''
    }
  },

  xmpp: {
    enabled: false,
    client: {
      jid: '',
      password: '',
      host: '',
      port: 5222,
      reconnect: true
    }
  },

  app: {
    psk: '',
    port: 7996,
    behindProxy: false,
    logIp: false,
    'listenersmininterval': 200, // Update listener counts on stream at most every X milliseconds
    'streamkeepaliveinterval': 60 * 60 * 1000, // Send a keepalive event this often
    // save the current state this often (in addition to on shutdown)
    'saveinterval': 5 * 60 * 1000
  }

};

// Export the config object based on the NODE_ENV
// ==============================================
module.exports = _.merge(
  all,
    require('./' + process.env.NODE_ENV + '.js') || {});<|endoftext|>


<commit_before>var queues = require('../models/GameMatchmaker.js');
var gameMgmnt = require('../models/GameManagement.js');
var _ = require('underscore');
var validator = require('./ValidateObjectController');

exports.MatchmakingController = function(){

};
// recieves inital queue request, validates it and passes it on to matchmaking
exports.MatchmakingController.joinMatchmaking = function(player, game, response){
	validator.ValidateArgs(arguments, Object, Object, Function);
	var gameList =[];
	var result = {};
	gameMgmnt.availableGames(function(gList){gameList = gList;});
	if(this.gameValidate(gameList,game)){ // make sure the game the client asks to queue for is a game we actually support.
		queues.GameMatchmaker.joinQueue(player,game,function(){
			this.Match(player,game,function(gameObj){result = gameObj;});
			});
		response(result);
	}
	else response("");
};

exports.MatchmakingController.emptyFunction = function(){
	return function(){
	};
};
exports.MatchmakingController.errLogging = function(){
	return function(err){
		if(err){
			console.log(err);
		}
	};
};

exports.MatchmakingController.Match= function(player,game,callback){
	validator.ValidateArgs(arguments, Object, Object, Function);
	var result = "";
	var gameList = [];
	queues.GameMatchmaker.getGameQueue(game, function(queue){gameList = queue});
	var numPlayers = 0;
	var playersFound = [];
	numPlayers = game['maxPlayers'];
	if(gameList.length < numPlayers){
		callback(""); // return no match found
		return;
	} else {
		//TODO elaborate on the matchmaking logic for other games
		for(var i = 0;i<numPlayers;i++){
			if(_.isEqual(gameList[i], player)){
				numPlayers++;
			}
			else{
				playersFound.push(gameList[i]);
			}
		}
		var gameObj = gameMgmnt.createMatch(0); // TODO once GameManager returns game IDs, get game IDs
	        for(i = 0; i< playersFound.length;i++){
			gameMgmnt.joinMatch(playersFound[i]['id'],gameObj, this.errLogging());
		}

		// remove both players from the matchmaking queue and return the game object;
		for(i = 0;i<playersFound.length;i++){
			queues.GameMatchmaker.removeFromQueue(playersFound[i]['player'],this.emptyFunction());
		}
		var gameBoard = {};
		gameMgmnt.getGameboard(gameObj,function(board){gameBoard = board});

		// TODO, push game board to both players and get the game started

		return callback(gameBoard);
	}
};

exports.MatchmakingController.gameValidate = function(games,game){
	validator.ValidateArgs(arguments, Object, Object);
	var result = false;
	var keys = Object.keys(games);
	for(var i = 0;i<keys.length;i++){
		if(_.isEqual(games[keys[i]],game)){
			result=true;
		}
	}
	return result;
};
<commit_msg>bug fixes with type checking<commit_after>var queues = require('../models/GameMatchmaker.js');
var gameMgmnt = require('../models/GameManagement.js');
var _ = require('underscore');
var validator = require('./ValidateObjectController');

exports.MatchmakingController = function(){

};
// recieves inital queue request, validates it and passes it on to matchmaking
exports.MatchmakingController.joinMatchmaking = function(player, game, response){
	validator.ValidateArgs(arguments, Object, Object, Function);
	var gameList =[];
	var result = {};
	gameMgmnt.availableGames(function(gList){gameList = gList;});
	if(this.gameValidate(gameList,game)){ // make sure the game the client asks to queue for is a game we actually support.
		queues.GameMatchmaker.joinQueue(player,game,function(){
			this.Match(player,game,function(gameObj){result = gameObj;});
			});
		response(result);
	}
	else {response("");}
};

exports.MatchmakingController.emptyFunction = function(){
	return function(){
	};
};
exports.MatchmakingController.errLogging = function(){
	return function(err){
		if(err){
			console.log(err);
		}
	};
};

exports.MatchmakingController.Match= function(player,game,callback){
	validator.ValidateArgs(arguments, Object, Object, Function);
	if(game == null || game === undefined || game == {}){
		throw new Error("Invalid game");
	}
	var result = "";
	var gameList = [];
	queues.GameMatchmaker.getGameQueue(game, function(queue){gameList = queue});
	var numPlayers = 0;
	var playersFound = [];
	numPlayers = game['maxPlayers'];
	if(gameList.length < numPlayers){
		callback(""); // return no match found
		return;
	} else {
		//TODO elaborate on the matchmaking logic for other games
		for(var i = 0;i<numPlayers;i++){
			if(_.isEqual(gameList[i], player)){
				numPlayers++;
			}
			else{
				playersFound.push(gameList[i]);
			}
		}
		var gameObj = gameMgmnt.createMatch(0); // TODO once GameManager returns game IDs, get game IDs
	        for(i = 0; i< playersFound.length;i++){
			gameMgmnt.joinMatch(playersFound[i]['id'],gameObj, this.errLogging());
		}

		// remove both players from the matchmaking queue and return the game object;
		for(i = 0;i<playersFound.length;i++){
			queues.GameMatchmaker.removeFromQueue(playersFound[i]['player'],this.emptyFunction());
		}
		var gameBoard = {};
		gameMgmnt.getGameboard(gameObj,function(board){gameBoard = board});

		// TODO, push game board to both players and get the game started

		return callback(gameBoard);
	}
};

exports.MatchmakingController.gameValidate = function(games,game){
	validator.ValidateArgs(arguments, Object, Object);
	var result = false;
	var keys = Object.keys(games);
	for(var i = 0;i<keys.length;i++){
		if(_.isEqual(games[keys[i]],game)){
			result=true;
		}
	}
	return result;
};
<|endoftext|>


<commit_before>'use strict'

module.exports = function(data) {
    return {
        getUserIncomeDetails(req, res) {
            return data.getAllUserIncomeData()
                .then((listings) => {
                    if (!listings) {
                        throw new Error('No items available');
                    }
                    res.status(200).json(listings);
                })
                .catch((err) => {
                    res.status(400).json({ message: err.message });
                });
        },
        updateUserIncomeDetailsById(req, res, next) {
            const errors = req.validationErrors();

            if (errors) {
                return res.redirect("/user-income");
            }
            UserIncome.findById(req.userIncome._id, (err, userIncome) => {
                if (err) {
                    return next(err);
                }
                userIncome.incomes.company = req.body.company || "";
                userIncome.incomes.amount = req.body.amount || "";
                userIncome.incomes.startDate = req.body.startDate || "";
                userIncome.incomes.accounts = req.body.accounts || "";
                userIncome.incomes.recurrence = req.body.recurrence || "";
                userIncome.save((err) => {
                    if (err) {
                        if (err.code === 11000) {
                            return res.redirect("/user-income");
                        }
                        return next(err);
                    }
                    res.redirect("/user-income");
                });
            });
        },
    }
}<commit_msg>fixed very bad TYPO!<commit_after>'use strict'

module.exports = function(data) {
    return {
        getUserIncomeDetails(req, res) {
            return data.getAllUserIncomeData()
                .then((listings) => {
                    if (!listings) {
                        throw new Error('No items available');
                    }
                    res.status(200).json(listings);
                })
                .catch((err) => {
                    res.status(400).json({ message: err.message });
                });
        },
        updateUserIncomeDetailsById(req, res, next) {
            const errors = req.validationErrors();

            if (errors) {
                return res.redirect("/user-income");
            }
            UserIncome.findById(req.userIncome.user_id, (err, userIncome) => {
                if (err) {
                    return next(err);
                }
                userIncome.incomes.company = req.body.company || "";
                userIncome.incomes.amount = req.body.amount || "";
                userIncome.incomes.startDate = req.body.startDate || "";
                userIncome.incomes.accounts = req.body.accounts || "";
                userIncome.incomes.recurrence = req.body.recurrence || "";
                userIncome.save((err) => {
                    if (err) {
                        if (err.code === 11000) {
                            return res.redirect("/user-income");
                        }
                        return next(err);
                    }
                    res.redirect("/user-income");
                });
            });
        },
    }
}<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var Game = require('../../models/game/game.model');
var UnpublishedGame = require('../../models/unpublishedGame/unpublishedGame.model');
var verifyToken = require('../login/verifyToken');
var validator = require('../../validator/validator');
var constants = require('../../config/constants.config');
var _ = require('lodash');
var logger = require('../../logger/logger');
var Report = require('../../models/report/report.model');
var Review = require('../../models/review/review.model');
var winston = require('winston');

module.exports = function (app) {
	var verifyPostRequest = function (req, res, next) {
		if (req.body._id) return res.status(422).json({message: 'An unpublishedGame can not be created with a given _id.'});
		next();
	};

	router.post('/unpublishedGames', verifyToken, verifyPostRequest, function (req, res) {
		var tmpGame = _.omit(req.body, ['rating', 'numberOfVotes', 'sumOfVotes', 'reviews', 'owner']);
		var unpublishedGame = new Game(_.extend(tmpGame, {owner: req.verified.id}));
		if (unpublishedGame.rules) {
			unpublishedGame.rules = unpublishedGame.rules.filter(function (v) { return v !== ''; });
		}
		if (unpublishedGame.alternativeRules) {
			unpublishedGame.alternativeRules = unpublishedGame.alternativeRules.filter(function (v) { return v !== ''; });
		}
		if (!req.body.parentGame) unpublishedGame.parentGame = undefined;
		unpublishedGame.save(function (err) {
			if (err) {
				logger.log('error', 'POST /unpublishedGames', err);
				return res.status(500).send();
			}
			unpublishedGame.populate('owner', 'username', function (err) {
				if (err) {
					logger.log('error', 'POST /unpublishedGames', err);
					return res.status(500).send();
				} else return res.status(201).json(unpublishedGame);
			});
		});
	});

	router.get('/users/:userId/unpublishedGames', verifyToken, function (req, res) {
		if (!validator.isValidId(req.params.userId)) return res.status(422).send();
		if (req.verified.id !== req.params.userId) return res.status(401).send();
		Game.find({owner: req.verified.id, published: false}, function (err, games) {
			if (err) {
				logger.log('error', 'GET /users/:userId/unpublishedGames', err);
				return res.status(500).send();
			} else return res.status(200).json(games);
		});
	});

	router.put('/unpublishedGames/:id', verifyToken, function (req, res) {
		if (!validator.isValidId(req.params.id)) return res.status(422).send();
		var tmpGame = _.omit(req.body, ['rating', 'numberOfVotes', 'sumOfVotes', 'reviews', 'owner']);
		if (tmpGame.parentGame === '') req.body.parentGame = undefined;
		if (tmpGame.rules) {
			tmpGame.rules = tmpGame.rules.filter(function (v) { return v !== ''; });
		}
		if (tmpGame.alternativeRules) {
			tmpGame.alternativeRules = tmpGame.alternativeRules.filter(function (v) { return v !== ''; });
		}
		if (tmpGame.pieces) {
			if (tmpGame.pieces.singles === '') tmpGame.pieces.singles = 0;
			if (tmpGame.pieces.doubles === '') tmpGame.pieces.doubles = 0;
			if (tmpGame.pieces.triples === '') tmpGame.pieces.triples = 0;
		}
		Game.findByIdAndUpdate(req.params.id, tmpGame, function (err, game) {
			if (err) {
				logger.log('error', 'PUT /unpublishedGames/:id', err);
				return res.status(500).send();
			} else if (!game) return res.status(404).send();
			else return res.status(200).json(game);
		});
	});

	router.delete('/unpublishedGames/:id', verifyToken, function (req, res) {
		if (!validator.isValidId(req.params.id)) return res.status(422).send();
		Game.findOne({_id: req.params.id, published: false}, function (err, game) {
			if (err) {
				logger.log('error', 'DELETE /unbpublishedGames/:id', err);
				return res.status(500).send();
			}
			if (!game) return res.status(404).send();
			if (!game.owner.equals(req.verified.id)) return res.status(401).send();
			Game.remove({_id: req.params.id}, function (err, game) {
				if (err) {
					logger.log('error', 'DELETE /unpublishedGames/:id', err);
					return res.status(500).send();
				} else if (!game) return res.status(404).send();
				else {
					Report.removePossibleReports(req.params.id, Report.types.UNPUBLISHED_GAME); // if the game has any reports, these are removed
					Review.removePossibleReviews(req.params.id); // if the gme has ane reviews, these are removed
					return res.status(200).json();
				}
			});
		});
	});

	router.post('/unpublishedGames/:id/publish', verifyToken, function (req, res) {
		if (!validator.isValidId(req.params.id)) return res.status(422).send();
		Game.findOne({_id: req.params.id, published: false}, function (err, game) {
			if (err) return res.status(500).send();
			if (!game) return res.status(404).send();
			if (!game.owner.equals(req.verified.id)) return res.status(401).send();
			if (!game.title || !game.shortDescription) return res.status(422).send();
			Game.findByIdAndUpdate(game._id, {$set: {published: true}}, function (err, publishedGame) {
				if (err || !publishedGame) {
					logger.log('error', 'POST /unpublishedGames/:id/publish', err);
					return res.status(500).send();
				} else {
					return res.status(200).json(publishedGame);
				}
			})
		});
	});

	return router;
};
<commit_msg>Fix bug for publishing games<commit_after>var express = require('express');
var router = express.Router();
var Game = require('../../models/game/game.model');
var UnpublishedGame = require('../../models/unpublishedGame/unpublishedGame.model');
var verifyToken = require('../login/verifyToken');
var validator = require('../../validator/validator');
var constants = require('../../config/constants.config');
var _ = require('lodash');
var logger = require('../../logger/logger');
var Report = require('../../models/report/report.model');
var Review = require('../../models/review/review.model');
var winston = require('winston');

module.exports = function (app) {
	var verifyPostRequest = function (req, res, next) {
		if (req.body._id) return res.status(422).json({message: 'An unpublishedGame can not be created with a given _id.'});
		next();
	};

	router.post('/unpublishedGames', verifyToken, verifyPostRequest, function (req, res) {
		var tmpGame = _.omit(req.body, ['rating', 'numberOfVotes', 'sumOfVotes', 'reviews', 'owner']);
		var unpublishedGame = new Game(_.extend(tmpGame, {owner: req.verified.id}));
		if (unpublishedGame.rules) {
			unpublishedGame.rules = unpublishedGame.rules.filter(function (v) { return v !== ''; });
		}
		if (unpublishedGame.alternativeRules) {
			unpublishedGame.alternativeRules = unpublishedGame.alternativeRules.filter(function (v) { return v !== ''; });
		}
		if (!req.body.parentGame) unpublishedGame.parentGame = undefined;
		unpublishedGame.save(function (err) {
			if (err) {
				logger.log('error', 'POST /unpublishedGames', err);
				return res.status(500).send();
			}
			unpublishedGame.populate('owner', 'username', function (err) {
				if (err) {
					logger.log('error', 'POST /unpublishedGames', err);
					return res.status(500).send();
				} else return res.status(201).json(unpublishedGame);
			});
		});
	});

	router.get('/users/:userId/unpublishedGames', verifyToken, function (req, res) {
		if (!validator.isValidId(req.params.userId)) return res.status(422).send();
		if (req.verified.id !== req.params.userId) return res.status(401).send();
		Game.find({owner: req.verified.id, published: false}, function (err, games) {
			if (err) {
				logger.log('error', 'GET /users/:userId/unpublishedGames', err);
				return res.status(500).send();
			} else return res.status(200).json(games);
		});
	});

	router.put('/unpublishedGames/:id', verifyToken, function (req, res) {
		if (!validator.isValidId(req.params.id)) return res.status(422).send();
		var tmpGame = _.omit(req.body, ['rating', 'numberOfVotes', 'sumOfVotes', 'reviews', 'owner']);
		if (tmpGame.parentGame === '') req.body.parentGame = undefined;
		if (tmpGame.rules) {
			tmpGame.rules = tmpGame.rules.filter(function (v) { return v !== ''; });
		}
		if (tmpGame.alternativeRules) {
			tmpGame.alternativeRules = tmpGame.alternativeRules.filter(function (v) { return v !== ''; });
		}
		if (tmpGame.pieces) {
			if (tmpGame.pieces.singles === '') tmpGame.pieces.singles = 0;
			if (tmpGame.pieces.doubles === '') tmpGame.pieces.doubles = 0;
			if (tmpGame.pieces.triples === '') tmpGame.pieces.triples = 0;
		}
		Game.findByIdAndUpdate(req.params.id, tmpGame, function (err, game) {
			if (err) {
				logger.log('error', 'PUT /unpublishedGames/:id', err);
				return res.status(500).send();
			} else if (!game) return res.status(404).send();
			else return res.status(200).json(game);
		});
	});

	router.delete('/unpublishedGames/:id', verifyToken, function (req, res) {
		if (!validator.isValidId(req.params.id)) return res.status(422).send();
		Game.findOne({_id: req.params.id, published: false}, function (err, game) {
			if (err) {
				logger.log('error', 'DELETE /unbpublishedGames/:id', err);
				return res.status(500).send();
			}
			if (!game) return res.status(404).send();
			if (!game.owner.equals(req.verified.id)) return res.status(401).send();
			Game.remove({_id: req.params.id}, function (err, game) {
				if (err) {
					logger.log('error', 'DELETE /unpublishedGames/:id', err);
					return res.status(500).send();
				} else if (!game) return res.status(404).send();
				else {
					Report.removePossibleReports(req.params.id, Report.types.UNPUBLISHED_GAME); // if the game has any reports, these are removed
					Review.removePossibleReviews(req.params.id); // if the gme has ane reviews, these are removed
					return res.status(200).json();
				}
			});
		});
	});

	router.post('/unpublishedGames/:id/publish', verifyToken, function (req, res) {
		if (!validator.isValidId(req.params.id)) return res.status(422).send();
		Game.findOne({_id: req.params.id, published: false}, function (err, game) {
			if (err) return res.status(500).send();
			if (!game) return res.status(404).send();
			if (!game.owner.equals(req.verified.id)) return res.status(401).send();
			if (!game.title || !game.shortDescription) return res.status(422).send();
			Game.findByIdAndUpdate(game._id, {$set: {published: true}}, function (err, publishedGame) {
				if (err) {
					logger.log('error', 'POST /unpublishedGames/:id/publish', err);
					return res.status(500).send();
				} else {
					return res.status(200).json(publishedGame);
				}
			})
		});
	});

	return router;
};
<|endoftext|>


<commit_before>require('child_process').spawnSync('npm', ['build'], { stdio: 'inherit', cwd: 'client', shell: true });
<commit_msg>fixed built script<commit_after>require('child_process').spawnSync('npm run', ['build'], { stdio: 'inherit', cwd: 'client', shell: true });
<|endoftext|>


<commit_before>// @flow

const { logger } = require('@lagoon/commons/src/local-logging');

const { getSlackinfoForProject } = require('@lagoon/commons/src/api');

var IncomingWebhook = require('@slack/client').IncomingWebhook;

export type ChannelWrapper = {
  ack: (msg: Object) => void,
}

export type RabbitMQMsg = {
  content: Buffer,
  fields: Object,
  properties: Object,
};

export type Project = {
  slack: Object,
  name: string,
};

async function readFromRabbitMQ (msg: RabbitMQMsg, channelWrapperLogs: ChannelWrapper): Promise<void> {
  const {
    content,
    fields,
    properties,
  } = msg;

  const logMessage = JSON.parse(content.toString())

  const {
    severity,
    project,
    uuid,
    event,
    meta,
    message
  } = logMessage

  const appId = msg.properties.appId || ""

 logger.verbose(`received ${event}`, logMessage)

  switch (event) {

    case "github:pull_request:closed:handled":
    case "github:pull_request:opened:handled":
    case "github:pull_request:synchronize:handled":
    case "github:delete:handled":
    case "github:push:handled":
    case "bitbucket:repo:push:handled":
    case "gitlab:push:handled":
    case "rest:deploy:receive":
    case "rest:remove:receive":
    case "github:push:skipped":
    case "gitlab:push:skipped":
      sendToSlack(project, message, '#E8E8E8', ':information_source:', channelWrapperLogs, msg, appId)
      break;

    case "task:deploy-openshift:finished":
    case "task:remove-openshift:finished":
    case "task:remove-openshift-resources:finished":
    case "task:builddeploy-openshift:complete":
      sendToSlack(project, message, 'good', ':white_check_mark:', channelWrapperLogs, msg, appId)
      break;

    case "task:deploy-openshift:retry":
    case "task:remove-openshift:retry":
    case "task:remove-openshift-resources:retry":
      sendToSlack(project, message, 'warning', ':warning:', channelWrapperLogs, msg, appId)
      break;

    case "task:deploy-openshift:error":
    case "task:remove-openshift:error":
    case "task:remove-openshift-resources:error":
    case "task:builddeploy-openshift:failed":
      sendToSlack(project, message, 'danger', ':bangbang:', channelWrapperLogs, msg, appId)
      break;

    case "github:pull_request:closed:CannotDeleteProductionEnvironment":
    case "github:push:CannotDeleteProductionEnvironment":
    case "bitbucket:repo:push:CannotDeleteProductionEnvironment":
    case "gitlab:push:CannotDeleteProductionEnvironment":
    case "rest:remove:CannotDeleteProductionEnvironment":
      sendToSlack(project, message, 'warning', ':warning:', channelWrapperLogs, msg, appId)
      break;

    case "unresolvedProject:webhooks2tasks":
    case "unhandledWebhook":
    case "webhooks:receive":
    case "task:deploy-openshift:start":
    case "task:remove-openshift:start":
    case "task:remove-openshift-resources:start":
    case "task:builddeploy-openshift:running":
      // known logs entries that should never go to slack
      channelWrapperLogs.ack(msg)
      break;

    default:
      logger.info(`unhandled log message ${event} ${JSON.stringify(logMessage)}`)
      return channelWrapperLogs.ack(msg)
  }

}

const sendToSlack = async (project, message, color, emoji, channelWrapperLogs, msg, appId) => {

  let projectSlacks;
  try {
    projectSlacks = await getSlackinfoForProject(project)
  }
  catch (error) {
    logger.error(`No Slack information found, error: ${error}`)
    return channelWrapperLogs.ack(msg)
  }
  projectSlacks.forEach(async (projectSlack) => {
    await new IncomingWebhook(projectSlack.webhook, {
      channel: projectSlack.channel,
    }).send({
      attachments: [{
        text: `${emoji} ${message}`,
        color: color,
        "mrkdwn_in": ["pretext", "text", "fields"],
        footer: appId
      }]
    });
  });
  channelWrapperLogs.ack(msg)
  return
}

module.exports = readFromRabbitMQ;
<commit_msg>add bitbucket message slack handling.<commit_after>// @flow

const { logger } = require('@lagoon/commons/src/local-logging');

const { getSlackinfoForProject } = require('@lagoon/commons/src/api');

var IncomingWebhook = require('@slack/client').IncomingWebhook;

export type ChannelWrapper = {
  ack: (msg: Object) => void,
}

export type RabbitMQMsg = {
  content: Buffer,
  fields: Object,
  properties: Object,
};

export type Project = {
  slack: Object,
  name: string,
};

async function readFromRabbitMQ (msg: RabbitMQMsg, channelWrapperLogs: ChannelWrapper): Promise<void> {
  const {
    content,
    fields,
    properties,
  } = msg;

  const logMessage = JSON.parse(content.toString())

  const {
    severity,
    project,
    uuid,
    event,
    meta,
    message
  } = logMessage

  const appId = msg.properties.appId || ""

 logger.verbose(`received ${event}`, logMessage)

  switch (event) {

    case "github:pull_request:closed:handled":
    case "github:pull_request:opened:handled":
    case "github:pull_request:synchronize:handled":
    case "github:delete:handled":
    case "github:push:handled":
    case "bitbucket:repo:push:handled":
    case "gitlab:push:handled":
    case "rest:deploy:receive":
    case "rest:remove:receive":
    case "github:push:skipped":
    case "gitlab:push:skipped":
    case "bitbucket:push:skipped"
      sendToSlack(project, message, '#E8E8E8', ':information_source:', channelWrapperLogs, msg, appId)
      break;

    case "task:deploy-openshift:finished":
    case "task:remove-openshift:finished":
    case "task:remove-openshift-resources:finished":
    case "task:builddeploy-openshift:complete":
      sendToSlack(project, message, 'good', ':white_check_mark:', channelWrapperLogs, msg, appId)
      break;

    case "task:deploy-openshift:retry":
    case "task:remove-openshift:retry":
    case "task:remove-openshift-resources:retry":
      sendToSlack(project, message, 'warning', ':warning:', channelWrapperLogs, msg, appId)
      break;

    case "task:deploy-openshift:error":
    case "task:remove-openshift:error":
    case "task:remove-openshift-resources:error":
    case "task:builddeploy-openshift:failed":
      sendToSlack(project, message, 'danger', ':bangbang:', channelWrapperLogs, msg, appId)
      break;

    case "github:pull_request:closed:CannotDeleteProductionEnvironment":
    case "github:push:CannotDeleteProductionEnvironment":
    case "bitbucket:repo:push:CannotDeleteProductionEnvironment":
    case "gitlab:push:CannotDeleteProductionEnvironment":
    case "rest:remove:CannotDeleteProductionEnvironment":
      sendToSlack(project, message, 'warning', ':warning:', channelWrapperLogs, msg, appId)
      break;

    case "unresolvedProject:webhooks2tasks":
    case "unhandledWebhook":
    case "webhooks:receive":
    case "task:deploy-openshift:start":
    case "task:remove-openshift:start":
    case "task:remove-openshift-resources:start":
    case "task:builddeploy-openshift:running":
      // known logs entries that should never go to slack
      channelWrapperLogs.ack(msg)
      break;

    default:
      logger.info(`unhandled log message ${event} ${JSON.stringify(logMessage)}`)
      return channelWrapperLogs.ack(msg)
  }

}

const sendToSlack = async (project, message, color, emoji, channelWrapperLogs, msg, appId) => {

  let projectSlacks;
  try {
    projectSlacks = await getSlackinfoForProject(project)
  }
  catch (error) {
    logger.error(`No Slack information found, error: ${error}`)
    return channelWrapperLogs.ack(msg)
  }
  projectSlacks.forEach(async (projectSlack) => {
    await new IncomingWebhook(projectSlack.webhook, {
      channel: projectSlack.channel,
    }).send({
      attachments: [{
        text: `${emoji} ${message}`,
        color: color,
        "mrkdwn_in": ["pretext", "text", "fields"],
        footer: appId
      }]
    });
  });
  channelWrapperLogs.ack(msg)
  return
}

module.exports = readFromRabbitMQ;
<|endoftext|>