<commit_before>/*
 * Copyright (C) 2012-2013 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * LayerSelector
 * A generic component to retrieve the layers
 * @author Meine Toonen
 */
Ext.define ("viewer.components.LayerSelector",{
    extend: "viewer.components.Component",
    popupWin:null,
    layersInitialized: false,
    layerList : null,
    layerArray : null,
    layerselector : null,
    layerstore: null,
    div: null,
    // An array of layers whom visibility must be forced in the layerSelector
    forcedLayers : null,
    config: {
        viewerController: {},
        restriction : null,
        layers: null,
        useTabs: false,
        label: null,
        rememberSelection: false
    },
    constructor: function (conf){
        if(!conf.label){
            conf.label = 'Kies kaartlaag';
        }
        this.initConfig(conf);
        viewer.components.LayerSelector.superclass.constructor.call(this, this.config);

        this.forcedLayers = [];
        this.layerstore = Ext.create('Ext.data.Store', {
            fields: ['layerId', 'title','layer'],
            data : []
        });

        if(this.config.useTabs) {
            this.createTabs();
        } else {
            this.createCombobox();
        }

        var requestPath= actionBeans["layerlist"];
        var requestParams = {};
        requestParams[this.config.restriction]= true;
        requestParams["appId"]= FlamingoAppLoader.get("appId");
        var me = this;
        if(this.config.layers != null && this.config.layers.length > 0){
            requestParams["layers"]= this.config.layers;
            requestParams["hasConfiguredLayers"]= true;
        }

        Ext.Ajax.request({
            url: requestPath,
            timeout: 120000,
            params: requestParams,
            success: function ( result, request ) {
                me.layersInitialized = true;
                me.layerList = Ext.JSON.decode(result.responseText);
                me.initLayers();
            },
            failure: function(a,b,c) {
                Ext.MessageBox.alert("Foutmelding", "Er is een onbekende fout opgetreden waardoor de lijst met kaartlagen niet kan worden weergegeven");
            }
        });
        this.config.viewerController.mapComponent.getMap().addListener(viewer.viewercontroller.controller.Event.ON_LAYER_VISIBILITY_CHANGED, this.layerVisibilityChanged, this);
        return this;
    },

    createCombobox: function() {
        var comboboxConfig = {
            fieldLabel: this.config.label,
            emptyText:'Maak uw keuze',
            store: this.layerstore,
            queryMode: 'local',
            displayField: 'title',
            valueField: 'layer',
            listeners :{
                change:{
                    fn: this.changed,
                    scope: this
                }
            }
        };
        if(this.config.div) {
            comboboxConfig.renderTo = this.config.div;
        }
        if(this.config.padding) {
            comboboxConfig.padding = this.config.padding;
        }
        this.layerselector = Ext.create('Ext.form.ComboBox', comboboxConfig);
    },

    createTabs: function() {
        var tabConfig = {
            bodyStyle: {
                width: 0,
                height: 0,
                display: 'none'
            },
            listeners :{
                tabchange: {
                    fn: this.tabChanged,
                    scope: this
                }
            }
        };
        if(this.config.div) {
            tabConfig.renderTo = this.config.div;
        }
        if(this.config.padding) {
            tabConfig.padding = this.config.padding;
        }
        this.layerselector = Ext.create('Ext.tab.Panel', tabConfig);
    },

    getLayerSelector: function() {
        return this.layerselector;
    },
    /**
     * @param forcedLayer the application layer that needs to be forced
     */
    addForcedLayer : function (forcedLayer){
        var dupe = false;
        for ( var i = 0 ; i < this.forcedLayers.length; i++){
            if(this.forcedLayers[i] == forcedLayer){
                dupe = true;
                break;
            }
        }
        if(!dupe){
            this.forcedLayers.push(forcedLayer);
        }
    },
    removeForcedLayer : function (forcedLayer){
        for( var i = this.forcedLayers.length -1 ; i >= 0 ; i--){
            if(this.forcedLayers[i]==forcedLayer){
                this.forcedLayers.splice(i,1);
            }
        }
    },
    initLayers : function (hasBeenInitialized) {
        if(!this.layersInitialized) {
            return;
        }
        var remember = this.config.rememberSelection && hasBeenInitialized;
        var currentValue = this.getValue();
        this.layerArray = [];
        var visibleLayers = this.config.viewerController.getVisibleLayers();
        for(var i = 0 ; i < this.forcedLayers.length; i++){
            visibleLayers.push(this.forcedLayers[i].id);
        }
        this.layerstore.removeAll();
        if(this.config.useTabs) {
            this.layerselector.removeAll();
        }
        var addedLayers = 0;
        if(this.layerList != null){
            for (var i = 0 ; i < this.layerList.length ;i++){
                var l = this.layerList[i];
                for ( var j = 0 ; j < visibleLayers.length ;j++){
                    //var appLayer = this.config.viewerController.getAppLayerById(visibleLayers[j]);
                    if (visibleLayers[j] == l.id || visibleLayers[j] == (""+l.id)){
                        this.layerstore.add({
                            layerId: l.id,
                            title: l.alias || l.layerName,
                            layer: l
                        });
                        addedLayers++;
                        break;
                    }
                }
            }
        }
        if(addedLayers === 0) {
            // this.layerselector.inputEl.dom.placeholder='Geen kaartlagen beschikbaar';
            this.layerselector.setDisabled(true);
        } else {
            // this.layerselector.inputEl.dom.placeholder='Maak uw keuze';
            this.layerselector.setDisabled(false);
            if(this.config.useTabs) {
                this.initTabs(remember);
            }
        }
        if(remember) {
            var updated = this.updateValueById(currentValue.id);
            if(!updated) {
                this.clearSelection();
                this.selectFirstLayer();
            }
        }
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_LAYERSELECTOR_INITLAYERS,
                {store: this.layerstore, layers: this.layerList, hasBeenInitialized: hasBeenInitialized}, this);
    },

    initTabs: function(skipSetActiveTab) {
        var tabs = [];
        this.layerstore.each(function(val) {
            tabs.push({
                title: val.get('title'),
                itemId: "tab-" + val.get('layerId')
            });
        });
        this.layerselector.add(tabs);
        if(!skipSetActiveTab) this.layerselector.setActiveTab(0);
    },

    getLayerIdFromTab: function(tab) {
        if(!tab) {
            return null;
        }
        return tab.getItemId().replace("tab-", "");
    },

    tabChanged: function(tabPanel, newTab, prevTab) {
        var layerId = this.getLayerIdFromTab(newTab);
        var prevLayerId = this.getLayerIdFromTab(prevTab);
        var applicationLayer = this.findLayerInStore(layerId);
        var previousLayer = this.findLayerInStore(prevLayerId);
        this.changed(tabPanel, applicationLayer, previousLayer);
    },

    changed :function (combobox,appLayer,previousSelected){
        // Retrieve appLayer from config.viewerController. Because the applayers in the comboBox are not the same as in the viewercontroller but copies. So by retrieving the ones
        // from the ViewerController you get the correct appLayer
        var al = null;
        appLayer = this._validateAppLayer(appLayer);
        if(appLayer){
            al = this.config.viewerController.getAppLayerById(appLayer.id);
        }
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_LAYERSELECTOR_CHANGE,al,previousSelected,this);

    },
    /**
     * Retrieve the AppLayer that is selected.
     */
    getValue : function (){
        // Retrieve appLayer from viewerController. Because the applayers in the comboBox are not the same as in the viewercontroller but copies. So by retrieving the ones
        // from the ViewerController you get the correct appLayer
        var val = null;
        if(this.config.useTabs) {
            val = this.findLayerInStore(this.getLayerIdFromTab(this.layerselector.getActiveTab()));
        } else {
            val = this.layerselector.getValue();
        }
        val = this._validateAppLayer(val);
        if (val) {
            var al = this.config.viewerController.getAppLayerById(val.id);
            return al;
        }else{
            return null;
        }
    },
    /**
     * In Internet Explorer it is possible that this function is called with
     * string instead of appLayer object. In this case we try to find the layer by name in the store.
     *
     * @param {appLayer}| {String} appLayer the AppLayer to validate or possibly a string
     * @private
     *
     */
    _validateAppLayer: function (val) {
        if (typeof val === "string") {
            try {
                // Try to find the layer based on name.
                var layerIndex = this.layerstore.findBy(function (record) {
                    if (record.get('title') === val) {
                        return true;
                    }
                    return false;
                });
                if (layerIndex !== -1) {
                    val = this.layerstore.getAt(layerIndex).data.layer;
                } else {
                    val = null;
                }
            } catch (e) {
            }
        }
        return val;
    },
    setValue : function (appLayer) {
        if(this.config.useTabs) {
            this.layerselector.setActiveTab(this.layerselector.getComponent('tab-' + appLayer.get('layerId')));
            return;
        }
        this.layerselector.setValue(appLayer);
    },
    updateValueById: function(layerId) {
        if(this.config.useTabs) {
            var tab = this.layerselector.getComponent('tab-' + layerId);
            if(!tab) {
                return false;
            }
            this.layerselector.setActiveTab(tab);
            return true;
        }
        var record = this.layerstore.findRecord('layerId', layerId);
        if(!record) {
            return false;
        }
        this.layerselector.setValue(record);
        return true;
    },
    hasValue: function(appLayer) {
        return this.findLayerInStore(appLayer.id) !== null;
    },
    findLayerInStore: function(layerId) {
        var layer = null;
        this.layerstore.each(function(val) {
            if("" + val.get('layerId') === "" + layerId) { // compare values as string, layerId in store can be int, layerId is string in most cases
                layer = val.get('layer');
            }
        });
        return layer;
    },
    /**
     * Gets the store for the LayerSelector
     * @returns Ext.data.Store
     */
    getStore: function() {
        return this.layerstore;
    },
    /**
     * Get the number of visible layers in the LayerSelector
     * @returns int
     */
    getVisibleLayerCount: function() {
        return this.layerstore.getCount();
    },
    selectFirstLayer: function() {
        var visibleLayers = this.getVisibleLayerCount();
        if(visibleLayers === 0) {
            return;
        }
        this.setValue(this.layerstore.getAt(0));
    },
    clearSelection: function() {
        if(this.config.useTabs) {
            // Its not possible to clear the value for tabs, once a tab is selected, there is always a tab selected
            return;
        }
        this.layerselector.clearValue();
    },
    /**
     * @deprecated use getValue()
     */
    getSelectedAppLayer : function (){
        return this.getValue();
    },
    getExtComponents: function() {
        return [ this.layerselector.getId() ];
    },
    layerVisibilityChanged : function (map,object){
        this.initLayers(true);
    }
});
<commit_msg>Fixes issue with LayerSelector<commit_after>/*
 * Copyright (C) 2012-2013 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * LayerSelector
 * A generic component to retrieve the layers
 * @author Meine Toonen
 */
Ext.define ("viewer.components.LayerSelector",{
    extend: "viewer.components.Component",
    popupWin:null,
    layersInitialized: false,
    layerList : null,
    layerArray : null,
    layerselector : null,
    layerstore: null,
    div: null,
    // An array of layers whom visibility must be forced in the layerSelector
    forcedLayers : null,
    config: {
        viewerController: {},
        restriction : null,
        layers: null,
        useTabs: false,
        label: null,
        rememberSelection: false
    },
    constructor: function (conf){
        if(!conf.label){
            conf.label = 'Kies kaartlaag';
        }
        this.initConfig(conf);
        viewer.components.LayerSelector.superclass.constructor.call(this, this.config);

        this.forcedLayers = [];
        this.layerstore = Ext.create('Ext.data.Store', {
            fields: ['layerId', 'title','layer'],
            data : []
        });

        if(this.config.useTabs) {
            this.createTabs();
        } else {
            this.createCombobox();
        }

        var requestPath= actionBeans["layerlist"];
        var requestParams = {};
        requestParams[this.config.restriction]= true;
        requestParams["appId"]= FlamingoAppLoader.get("appId");
        var me = this;
        if(this.config.layers != null && this.config.layers.length > 0){
            requestParams["layers"]= this.config.layers;
            requestParams["hasConfiguredLayers"]= true;
        }

        Ext.Ajax.request({
            url: requestPath,
            timeout: 120000,
            params: requestParams,
            success: function ( result, request ) {
                me.layersInitialized = true;
                me.layerList = Ext.JSON.decode(result.responseText);
                me.initLayers();
            },
            failure: function(a,b,c) {
                Ext.MessageBox.alert("Foutmelding", "Er is een onbekende fout opgetreden waardoor de lijst met kaartlagen niet kan worden weergegeven");
            }
        });
        this.config.viewerController.mapComponent.getMap().addListener(viewer.viewercontroller.controller.Event.ON_LAYER_VISIBILITY_CHANGED, this.layerVisibilityChanged, this);
        return this;
    },

    createCombobox: function() {
        var comboboxConfig = {
            fieldLabel: this.config.label,
            emptyText:'Maak uw keuze',
            store: this.layerstore,
            queryMode: 'local',
            displayField: 'title',
            valueField: 'layer',
            listeners :{
                change:{
                    fn: this.changed,
                    scope: this
                }
            }
        };
        if(this.config.div) {
            comboboxConfig.renderTo = this.config.div;
        }
        if(this.config.padding) {
            comboboxConfig.padding = this.config.padding;
        }
        this.layerselector = Ext.create('Ext.form.ComboBox', comboboxConfig);
    },

    createTabs: function() {
        var tabConfig = {
            bodyStyle: {
                width: 0,
                height: 0,
                display: 'none'
            },
            listeners :{
                tabchange: {
                    fn: this.tabChanged,
                    scope: this
                }
            }
        };
        if(this.config.div) {
            tabConfig.renderTo = this.config.div;
        }
        if(this.config.padding) {
            tabConfig.padding = this.config.padding;
        }
        this.layerselector = Ext.create('Ext.tab.Panel', tabConfig);
    },

    getLayerSelector: function() {
        return this.layerselector;
    },
    /**
     * @param forcedLayer the application layer that needs to be forced
     */
    addForcedLayer : function (forcedLayer){
        var dupe = false;
        for ( var i = 0 ; i < this.forcedLayers.length; i++){
            if(this.forcedLayers[i] == forcedLayer){
                dupe = true;
                break;
            }
        }
        if(!dupe){
            this.forcedLayers.push(forcedLayer);
        }
    },
    removeForcedLayer : function (forcedLayer){
        for( var i = this.forcedLayers.length -1 ; i >= 0 ; i--){
            if(this.forcedLayers[i]==forcedLayer){
                this.forcedLayers.splice(i,1);
            }
        }
    },
    initLayers : function (hasBeenInitialized) {
        if(!this.layersInitialized) {
            return;
        }
        var currentValue = this.getValue();
        var remember = this.config.rememberSelection && hasBeenInitialized && currentValue;
        this.layerArray = [];
        var visibleLayers = this.config.viewerController.getVisibleLayers();
        for(var i = 0 ; i < this.forcedLayers.length; i++){
            visibleLayers.push(this.forcedLayers[i].id);
        }
        this.layerstore.removeAll();
        if(this.config.useTabs) {
            this.layerselector.removeAll();
        }
        var addedLayers = 0;
        if(this.layerList != null){
            for (var i = 0 ; i < this.layerList.length ;i++){
                var l = this.layerList[i];
                for ( var j = 0 ; j < visibleLayers.length ;j++){
                    //var appLayer = this.config.viewerController.getAppLayerById(visibleLayers[j]);
                    if (visibleLayers[j] == l.id || visibleLayers[j] == (""+l.id)){
                        this.layerstore.add({
                            layerId: l.id,
                            title: l.alias || l.layerName,
                            layer: l
                        });
                        addedLayers++;
                        break;
                    }
                }
            }
        }
        if(addedLayers === 0) {
            // this.layerselector.inputEl.dom.placeholder='Geen kaartlagen beschikbaar';
            this.layerselector.setDisabled(true);
        } else {
            // this.layerselector.inputEl.dom.placeholder='Maak uw keuze';
            this.layerselector.setDisabled(false);
            if(this.config.useTabs) {
                this.initTabs(remember);
            }
        }
        if(remember) {
            var updated = this.updateValueById(currentValue.id);
            if(!updated) {
                this.clearSelection();
                this.selectFirstLayer();
            }
        }
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_LAYERSELECTOR_INITLAYERS,
                {store: this.layerstore, layers: this.layerList, hasBeenInitialized: hasBeenInitialized}, this);
    },

    initTabs: function(skipSetActiveTab) {
        var tabs = [];
        this.layerstore.each(function(val) {
            tabs.push({
                title: val.get('title'),
                itemId: "tab-" + val.get('layerId')
            });
        });
        this.layerselector.add(tabs);
        if(!skipSetActiveTab) this.layerselector.setActiveTab(0);
    },

    getLayerIdFromTab: function(tab) {
        if(!tab) {
            return null;
        }
        return tab.getItemId().replace("tab-", "");
    },

    tabChanged: function(tabPanel, newTab, prevTab) {
        var layerId = this.getLayerIdFromTab(newTab);
        var prevLayerId = this.getLayerIdFromTab(prevTab);
        var applicationLayer = this.findLayerInStore(layerId);
        var previousLayer = this.findLayerInStore(prevLayerId);
        this.changed(tabPanel, applicationLayer, previousLayer);
    },

    changed :function (combobox,appLayer,previousSelected){
        // Retrieve appLayer from config.viewerController. Because the applayers in the comboBox are not the same as in the viewercontroller but copies. So by retrieving the ones
        // from the ViewerController you get the correct appLayer
        var al = null;
        appLayer = this._validateAppLayer(appLayer);
        if(appLayer){
            al = this.config.viewerController.getAppLayerById(appLayer.id);
        }
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_LAYERSELECTOR_CHANGE,al,previousSelected,this);

    },
    /**
     * Retrieve the AppLayer that is selected.
     */
    getValue : function (){
        // Retrieve appLayer from viewerController. Because the applayers in the comboBox are not the same as in the viewercontroller but copies. So by retrieving the ones
        // from the ViewerController you get the correct appLayer
        var val = null;
        if(this.config.useTabs) {
            val = this.findLayerInStore(this.getLayerIdFromTab(this.layerselector.getActiveTab()));
        } else {
            val = this.layerselector.getValue();
        }
        val = this._validateAppLayer(val);
        if (val) {
            var al = this.config.viewerController.getAppLayerById(val.id);
            return al;
        }else{
            return null;
        }
    },
    /**
     * In Internet Explorer it is possible that this function is called with
     * string instead of appLayer object. In this case we try to find the layer by name in the store.
     *
     * @param {appLayer}| {String} appLayer the AppLayer to validate or possibly a string
     * @private
     *
     */
    _validateAppLayer: function (val) {
        if (typeof val === "string") {
            try {
                // Try to find the layer based on name.
                var layerIndex = this.layerstore.findBy(function (record) {
                    if (record.get('title') === val) {
                        return true;
                    }
                    return false;
                });
                if (layerIndex !== -1) {
                    val = this.layerstore.getAt(layerIndex).data.layer;
                } else {
                    val = null;
                }
            } catch (e) {
            }
        }
        return val;
    },
    setValue : function (appLayer) {
        if(this.config.useTabs) {
            this.layerselector.setActiveTab(this.layerselector.getComponent('tab-' + appLayer.get('layerId')));
            return;
        }
        this.layerselector.setValue(appLayer);
    },
    updateValueById: function(layerId) {
        if(this.config.useTabs) {
            var tab = this.layerselector.getComponent('tab-' + layerId);
            if(!tab) {
                return false;
            }
            this.layerselector.setActiveTab(tab);
            return true;
        }
        var record = this.layerstore.findRecord('layerId', layerId);
        if(!record) {
            return false;
        }
        this.layerselector.setValue(record);
        return true;
    },
    hasValue: function(appLayer) {
        return this.findLayerInStore(appLayer.id) !== null;
    },
    findLayerInStore: function(layerId) {
        var layer = null;
        this.layerstore.each(function(val) {
            if("" + val.get('layerId') === "" + layerId) { // compare values as string, layerId in store can be int, layerId is string in most cases
                layer = val.get('layer');
            }
        });
        return layer;
    },
    /**
     * Gets the store for the LayerSelector
     * @returns Ext.data.Store
     */
    getStore: function() {
        return this.layerstore;
    },
    /**
     * Get the number of visible layers in the LayerSelector
     * @returns int
     */
    getVisibleLayerCount: function() {
        return this.layerstore.getCount();
    },
    selectFirstLayer: function() {
        var visibleLayers = this.getVisibleLayerCount();
        if(visibleLayers === 0) {
            return;
        }
        this.setValue(this.layerstore.getAt(0));
    },
    clearSelection: function() {
        if(this.config.useTabs) {
            // Its not possible to clear the value for tabs, once a tab is selected, there is always a tab selected
            return;
        }
        this.layerselector.clearValue();
    },
    /**
     * @deprecated use getValue()
     */
    getSelectedAppLayer : function (){
        return this.getValue();
    },
    getExtComponents: function() {
        return [ this.layerselector.getId() ];
    },
    layerVisibilityChanged : function (map,object){
        this.initLayers(true);
    }
});
<|endoftext|>


<commit_before>(function(){
	const WSHOST = 'websockethost:port';
	const CHARCOUNT = 20;
	var ws, ws2,
		output = JSON.parse(localStorage.getItem('messages'))||[],
		lines = {
			'buildname': 'BUILDALIAS'
		},
		render = function(data){
			if(!lines[data.project]) return;
			if(output.length === Board.rows.length){
				output.pop();
			}

			var projectNumber = ' #' + data.number,
				projectName = lines[data.project].substring(0, CHARCOUNT - projectNumber.length);

			output.unshift(projectName.rpad(' ', CHARCOUNT - projectNumber.length) + projectNumber + data.result[0]);

			Board.setMessage(output);
			localStorage.setItem('messages', JSON.stringify(output));
		};

	var connect = function(){
	    if(ws) ws.close();

	    ws = new WebSocket('ws://' + HOST + '/jenkins'),

        ws.onmessage = function(msg) {
    		var data = JSON.parse(msg.data);

    		render(data);
    	};

    	setInterval(function(){
    	    ws.send('ping');
    	}, 5000);
	};

    connect();

	Board.bind('start', function(){
		Board.setMessage(output);
	});
})();<commit_msg>retab and linting<commit_after>/*global Board*/
(function(){
  var WSHOST = 'websockethost:port',
    CHARCOUNT = 20,
    ws, ws2,
    output = JSON.parse(localStorage.getItem('messages'))||[],
    lines = {
      'buildname': 'BUILDALIAS'
    },
    render = function(data){
      if (!lines[data.project]) return;
      if (output.length === Board.rows.length){
        output.pop();
      }

      var projectNumber = ' #' + data.number,
          projectName = lines[data.project].substring(0, CHARCOUNT - projectNumber.length);

      output.unshift(projectName.rpad(' ', CHARCOUNT - projectNumber.length) + projectNumber + data.result[0]);

      Board.setMessage(output);
      localStorage.setItem('messages', JSON.stringify(output));
  };

  var connect = function(){
    if(ws) ws.close();

    ws = new WebSocket('ws://' + WSHOST + '/jenkins'),
        ws.onmessage = function(msg) {
        var data = JSON.parse(msg.data);

        render(data);
    };

    setInterval(function(){
      ws.send('ping');
    }, 5000);
  };

  connect();

  Board.bind('start', function(){
    Board.setMessage(output);
  });
})();
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var morgan = require('morgan');
const bodyParser = require('body-parser');
var User = require('./db/User');
var application_root = __dirname,
    path = require("path"),
    mongoose = require('mongoose');
app.use(morgan('combined'));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost/do_db');
var db = mongoose.connection;
db.on('error', function () {
  console.log('connection error');
});
db.once('open', function () {
  console.log('Db connected...');
});
app.use(express.static(path.join(application_root, "public")));
app.post('/login', function (req, resp, next) {
  console.log('hello login');
  resp.send('okay');
});
app.post('/register', function (req, resp, next) {
  var testUser = new User();
  console.log('hello /register', req.body.name);
  resp.send('okay');
});
app.get('/hello', function (request, response, next) {
  // response.send("I'm hanifa");
  var todo;
  todo = new Todo({
    text: 'hanifa',
    done: 'everything',
    order: 'pizza'
  });
  todo.save(function(err) {
    if (!err) {
      return console.log("created");
    }
  });
  return response.send(todo);
});
app.post('/hello', function (request, response) {
  console.log('hello world', request.body);
  response.send("I'm hanifa");
});
app.get('/users', function (request, response, next) {

});
app.listen(3000);
<commit_msg>adding method to cors request<commit_after>var express = require('express');
var app = express();
var morgan = require('morgan');
const bodyParser = require('body-parser');
var User = require('./db/User');
var application_root = __dirname,
    path = require("path"),
    mongoose = require('mongoose');
app.use(morgan('combined'));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost/do_db');
var db = mongoose.connection;
db.on('error', function () {
  console.log('connection error');
});
db.once('open', function () {
  console.log('Db connected...');
});
app.use(express.static(path.join(application_root, "public")));
app.post('/login', function (req, resp, next) {
  console.log('hello login');
  resp.send('okay');
});
app.post('/register', function (req, resp, next) {
  var testUser = new User();
  if (User.find({username: req.body.username})) {
    console.log('User already exist', User.findOne({username: req.body.username}));
  } else {
    console.log('Unique user');
  }
  console.log('hello /register', req.body.name);
  resp.send('okay');
});
app.get('/users', function (request, response, next) {

});
app.listen(3000);
<|endoftext|>


<commit_before>import Loading from 'components/loading'

function plugin(Vue) {
    if(plugin.installed){
        return
    }

    let Component, component, container, propsData

    propsData = {
        visible: false
    }

    Component = Vue.extend(Loading)
    container = document.createElement('div')
    document.getElementsByTagName('body')[0].appendChild(container)
    component = new Component({propsData}).$mount(container)

    function method(visible, text) {
        if(text) {
            component.text = text
        }

        component.visible = visible
    }

    Vue.loading = method
    Vue.prototype.$loading = method
}

if(typeof window !== 'undefined' && window.Vue){
    window.Vue.use(plugin)
}

module.exports = plugin
<commit_msg>add fallback text<commit_after>import Loading from 'components/loading'

function plugin(Vue) {
    if(plugin.installed){
        return
    }

    let Component, component, container, propsData

    propsData = {
        visible: false
    }

    Component = Vue.extend(Loading)
    container = document.createElement('div')
    document.getElementsByTagName('body')[0].appendChild(container)
    component = new Component({propsData}).$mount(container)

    function method(visible, text) {
        if(text) {
            component.text = text
        }else {
            component.text = '数据加载中'
        }

        component.visible = visible
    }

    Vue.loading = method
    Vue.prototype.$loading = method
}

if(typeof window !== 'undefined' && window.Vue){
    window.Vue.use(plugin)
}

module.exports = plugin
<|endoftext|>


<commit_before>const electron, { session } = require('electron');
const Positioner = require('electron-positioner');
const ipc = require('node-ipc');
ipc.config.id = 'screenCastWindow';
ipc.config.retry = 1500;
ipc.config.socketRoot = 'tmp';
ipc.config.networkHost = 'localhost';
ipc.config.appSpace = 'MMM-Screencast';
const url = process.argv[2];
const position = process.argv[3];
const width = parseInt(process.argv[4], 10);
const height = parseInt(process.argv[5], 10);

// more useragents here: https://developers.whatismybrowser.com/useragents/explore/operating_platform/smart-tv/
const userAgent = 'Mozilla/5.0 (SMART-TV; X11; Linux armv7l) AppleWebKit/537.42 (KHTML, like Gecko) Chromium/25.0.1349.2 Chrome/25.0.1349.2 Safari/537.42';

ipc.serve(`/${ipc.config.socketRoot}/${ipc.config.appSpace}.${ipc.config.id}`, () => {
  ipc.server.on('quit', (data, socket) => {
    ipc.server.emit(socket, 'quit');
    app.quit();
    process.exit();
  });
});

const app = electron.app;
session.defaultSession.setUserAgent(userAgent);

app.once('ready', function () {
  const windowOptions = {
    maxHeight: height,
    maxWidth: width,
    resize: false,
    width: width,
    height: height,
    darkTheme: true,
    alwayOnTop: true,
    show: false,
    frame: false,
    zoomFactor: 1.0,
    focusable: false
  };

  const screenCastWindow = new electron.BrowserWindow(windowOptions);

  const positioner = new Positioner(screenCastWindow)
  positioner.move(position)

  screenCastWindow.loadURL(url)

  // Show window when page is ready
  screenCastWindow.once('ready-to-show', function () {
    screenCastWindow.show();
  });

});

ipc.server.start();
<commit_msg>updated user agent<commit_after>const electron = require('electron');
const Positioner = require('electron-positioner');
const ipc = require('node-ipc');
ipc.config.id = 'screenCastWindow';
ipc.config.retry = 1500;
ipc.config.socketRoot = 'tmp';
ipc.config.networkHost = 'localhost';
ipc.config.appSpace = 'MMM-Screencast';

const url = process.argv[2];
const position = process.argv[3];
const width = parseInt(process.argv[4], 10);
const height = parseInt(process.argv[5], 10);

// more useragents here: https://developers.whatismybrowser.com/useragents/explore/operating_platform/smart-tv/
const userAgent = 'Mozilla/5.0 (SMART-TV; Linux; Tizen 2.4.0) AppleWebkit/538.1 (KHTML, like Gecko) SamsungBrowser/1.1 TV Safari/538.1';

ipc.serve(`/${ipc.config.socketRoot}/${ipc.config.appSpace}.${ipc.config.id}`, () => {
  ipc.server.on('quit', (data, socket) => {
    ipc.server.emit(socket, 'quit');
    app.quit();
    process.exit();
  });
});

const app = electron.app;

app.once('ready', function () {
  electron.session.defaultSession.setUserAgent(userAgent);

  const windowOptions = {
    maxHeight: height,
    maxWidth: width,
    resize: false,
    width: width,
    height: height,
    darkTheme: true,
    alwayOnTop: true,
    show: false,
    frame: false,
    zoomFactor: 1.0,
    focusable: false
  };
  const screenCastWindow = new electron.BrowserWindow(windowOptions);

  const positioner = new Positioner(screenCastWindow)
  positioner.move(position)

  screenCastWindow.loadURL(url)

  // Show window when page is ready
  screenCastWindow.once('ready-to-show', function () {
    screenCastWindow.show();
  });

});

ipc.server.start();
<|endoftext|>


<commit_before>// TODO: add support for readFile -> readAsData
// TODO: add support for readFile -> readAsBinaryString
// TODO: add support for readFile -> readAsArrayBuffer
// TODO: add functionality to define storage size in the getFilesystem() -> requestFileSystem() method
// TODO: add documentation for FileError types
// TODO: add abort() option to downloadFile and uploadFile methods.
// TODO: add support for downloadFile and uploadFile options. (or detailed documentation) -> for fileKey, fileName, mimeType, headers
// TODO: add support for onprogress property

angular.module('ngCordova.plugins.file', [])

//Filesystem (checkDir, createDir, checkFile, creatFile, removeFile, writeFile, readFile)
  .factory('$cordovaFile', ['$q', function ($q) {

    return {
      checkDir: function (dir) {
        var q = $q.defer();

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getDirectory(dir, {create: false},
              //Dir exists
              function () {
                q.resolve();
              },
              //Dir doesn't exist
              function () {
                q.reject();
              }
            );
          }
        );

        return q.promise;
      },

      createDir: function (dir, replaceBOOL) {
        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getDirectory(dir, {create: true, exclusive: replaceBOOL});
          }
        );
      },

      checkFile: function (filePath) {
        var q = $q.defer();

        // Backward compatibility for previous function checkFile(dir, file)
        if (arguments.length == 2) {
            filePath = '/' + filePath + '/' + arguments[1];
        }

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: false},
              // File exists
              function () {
                q.resolve();
              },
              // File doesn't exist
              function () {
                q.reject();
              }
            );
          }
        );

        return q.promise;
      },

      createFile: function (filePath, replaceBOOL) {
        // Backward compatibility for previous function createFile(dir, file, replaceBOOL)
        if (arguments.length == 3) {
            filePath = '/' + filePath + '/' + arguments[1];
            replaceBOOL = arguments[2];
        }

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: true, exclusive: replaceBOOL},
              function (success) {

              },
              function (err) {

              });
          }
        );
      },

      removeFile: function (filePath) {
        var q = $q.defer();

        // Backward compatibility for previous function removeFile(dir, file)
        if (arguments.length == 2) {
            filePath = '/' + filePath + '/' + arguments[1];
        }

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: false}, function (fileEntry) {
              fileEntry.remove(function () {
                q.resolve();
              });
            });
          }
        );

        return q.promise;
      },

      writeFile: function (filePath, data) {
        var q = $q.defer();

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: true},
              function (fileEntry) {
                fileEntry.createWriter(
                  function (fileWriter) {
                    fileWriter.onwriteend = function(evt) {
                      q.resolve(evt);
                    }
                    fileWriter.write(data);
                  },
                  function (error) {
                    q.reject(error);
                  });
              }
            );
          }
        );

        return q.promise;
      },

      readFile: function (filePath) {
        var q = $q.defer();

        // Backward compatibility for previous function readFile(dir, file)
        if (arguments.length == 2) {
            filePath = '/' + filePath + '/' + arguments[1];
        }

        getFilesystem().then(
          function (filesystem) {

            filesystem.root.getFile(filePath, {create: false},
              // success
              function (fileEntry) {
                fileEntry.file(function (file) {
                  var reader = new FileReader();
                  reader.onloadend = function () {
                    q.resolve(this.result);
                  };

                  reader.readAsText(file);
                });
              },
              // error
              function (error) {
                q.reject(error);
              });
          }
        );

        return q.promise;
      },

      readFileMetadata: function (filePath) {
        var q = $q.defer();

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: false},
              // success
              function (fileEntry) {
                fileEntry.file(function (file) {
                  q.resolve(file);
                });
              },
              // error
              function (error) {
                q.reject(error);
              });
          }
        );

        return q.promise;
      },

      downloadFile: function (source, filePath, trustAllHosts, options) {
        var q = $q.defer();
        var fileTransfer = new FileTransfer();
        var uri = encodeURI(source);

        fileTransfer.onprogress = function(progressEvent) {
            q.notify(progressEvent);
        };

        fileTransfer.download(
          uri,
          filePath,
          function (entry) {
            q.resolve(entry);
          },
          function (error) {
            q.reject(error);
          },
          trustAllHosts, options);

          return q.promise;
      },

      uploadFile: function (server, filePath, options) {
        var q = $q.defer();
        var fileTransfer = new FileTransfer();
        var uri = encodeURI(server);

        fileTransfer.onprogress = function(progressEvent) {
            q.notify(progressEvent);
        };

        fileTransfer.upload(
          filePath,
          uri,
          function (result) {
            q.resolve(result);
          },
          function (error) {
            q.reject(error);
          },
          options)

          return q.promise
      }

    };

    function getFilesystem() {
      var q = $q.defer();

      window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024, function (filesystem) {
          q.resolve(filesystem);
        },
        function (err) {
          q.reject(err);
        });

      return q.promise;
    }
  }]);<commit_msg>Adding listDir function in file plugin wrapper, to list files in a given directory<commit_after>// TODO: add support for readFile -> readAsData
// TODO: add support for readFile -> readAsBinaryString
// TODO: add support for readFile -> readAsArrayBuffer
// TODO: add functionality to define storage size in the getFilesystem() -> requestFileSystem() method
// TODO: add documentation for FileError types
// TODO: add abort() option to downloadFile and uploadFile methods.
// TODO: add support for downloadFile and uploadFile options. (or detailed documentation) -> for fileKey, fileName, mimeType, headers
// TODO: add support for onprogress property

angular.module('ngCordova.plugins.file', [])

//Filesystem (checkDir, createDir, checkFile, creatFile, removeFile, writeFile, readFile)
  .factory('$cordovaFile', ['$q', function ($q) {

    return {
      checkDir: function (dir) {
        var q = $q.defer();

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getDirectory(dir, {create: false},
              //Dir exists
              function () {
                q.resolve();
              },
              //Dir doesn't exist
              function () {
                q.reject();
              }
            );
          }
        );

        return q.promise;
      },

      createDir: function (dir, replaceBOOL) {
        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getDirectory(dir, {create: true, exclusive: replaceBOOL});
          }
        );
      },

      listDir: function(filePath) {
        var q = $q.defer();

        getFilesystem().then(
          function(filesystem) {
            filesystem.root.getDirectory(filePath, {create: false}, function(parent) {
              var reader = parent.createReader();
              reader.readEntries(
                  function(entries) {
                    q.resolve(entries);
                  },
                  function() {
                    q.reject('DIR_READ_ERROR : ' + filePath);
                  }
              );
            }, function() {
                q.reject('DIR_NOT_FOUND : ' + filePath);
            });
          }
        );

        return q.promise;
      },

      checkFile: function (filePath) {
        var q = $q.defer();

        // Backward compatibility for previous function checkFile(dir, file)
        if (arguments.length == 2) {
            filePath = '/' + filePath + '/' + arguments[1];
        }

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: false},
              // File exists
              function () {
                q.resolve();
              },
              // File doesn't exist
              function () {
                q.reject();
              }
            );
          }
        );

        return q.promise;
      },

      createFile: function (filePath, replaceBOOL) {
        // Backward compatibility for previous function createFile(dir, file, replaceBOOL)
        if (arguments.length == 3) {
            filePath = '/' + filePath + '/' + arguments[1];
            replaceBOOL = arguments[2];
        }

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: true, exclusive: replaceBOOL},
              function (success) {

              },
              function (err) {

              });
          }
        );
      },

      removeFile: function (filePath) {
        var q = $q.defer();

        // Backward compatibility for previous function removeFile(dir, file)
        if (arguments.length == 2) {
            filePath = '/' + filePath + '/' + arguments[1];
        }

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: false}, function (fileEntry) {
              fileEntry.remove(function () {
                q.resolve();
              });
            });
          }
        );

        return q.promise;
      },

      writeFile: function (filePath, data) {
        var q = $q.defer();

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: true},
              function (fileEntry) {
                fileEntry.createWriter(
                  function (fileWriter) {
                    fileWriter.onwriteend = function(evt) {
                      q.resolve(evt);
                    }
                    fileWriter.write(data);
                  },
                  function (error) {
                    q.reject(error);
                  });
              }
            );
          }
        );

        return q.promise;
      },

      readFile: function (filePath) {
        var q = $q.defer();

        // Backward compatibility for previous function readFile(dir, file)
        if (arguments.length == 2) {
            filePath = '/' + filePath + '/' + arguments[1];
        }

        getFilesystem().then(
          function (filesystem) {

            filesystem.root.getFile(filePath, {create: false},
              // success
              function (fileEntry) {
                fileEntry.file(function (file) {
                  var reader = new FileReader();
                  reader.onloadend = function () {
                    q.resolve(this.result);
                  };

                  reader.readAsText(file);
                });
              },
              // error
              function (error) {
                q.reject(error);
              });
          }
        );

        return q.promise;
      },

      readFileMetadata: function (filePath) {
        var q = $q.defer();

        getFilesystem().then(
          function (filesystem) {
            filesystem.root.getFile(filePath, {create: false},
              // success
              function (fileEntry) {
                fileEntry.file(function (file) {
                  q.resolve(file);
                });
              },
              // error
              function (error) {
                q.reject(error);
              });
          }
        );

        return q.promise;
      },

      downloadFile: function (source, filePath, trustAllHosts, options) {
        var q = $q.defer();
        var fileTransfer = new FileTransfer();
        var uri = encodeURI(source);

        fileTransfer.onprogress = function(progressEvent) {
            q.notify(progressEvent);
        };

        fileTransfer.download(
          uri,
          filePath,
          function (entry) {
            q.resolve(entry);
          },
          function (error) {
            q.reject(error);
          },
          trustAllHosts, options);

          return q.promise;
      },

      uploadFile: function (server, filePath, options) {
        var q = $q.defer();
        var fileTransfer = new FileTransfer();
        var uri = encodeURI(server);

        fileTransfer.onprogress = function(progressEvent) {
            q.notify(progressEvent);
        };

        fileTransfer.upload(
          filePath,
          uri,
          function (result) {
            q.resolve(result);
          },
          function (error) {
            q.reject(error);
          },
          options)

          return q.promise
      }

    };

    function getFilesystem() {
      var q = $q.defer();

      window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024, function (filesystem) {
          q.resolve(filesystem);
        },
        function (err) {
          q.reject(err);
        });

      return q.promise;
    }
  }]);<|endoftext|>


<commit_before>var express = require('express');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var url = require('url');
var sass = require('node-sass');
var app = express();
var _ = require('underscore');
var configServer = require('./config/server.js');
var configClient = require('./config/client.js');

app.use(sass.middleware({
  src: __dirname + '/app',
  debug: true
}));

app.use(express.static('app'));

var bodyParser = require('body-parser');
app.use( bodyParser.json() );

app.get('/config', function (req, res) {
  res.send(configClient);
});

app.get('/request_code', function (req, res) {
  if(req.query.requestPrivateRepositories){
    res.redirect('https://github.com/login/oauth/authorize?client_id=' + configServer.clientId + '&scope=repo');
  } else {
    res.redirect('https://github.com/login/oauth/authorize?client_id=' + configServer.clientId + '&scope=public_repo');
  }
});

app.get('/request_auth_token', function (req, res) {
  console.log('==== /request_auth_token ====');
  var getAuthTokenUrl = 'https://github.com/login/oauth/access_token?' +
    'client_id=' + configServer.clientId +
    '&client_secret=' + configServer.clientSecret +
    '&code=' + req.query.code;

  xhr = new XMLHttpRequest();
  xhr.open('POST', getAuthTokenUrl, false);
  xhr.send();

  var fakeUrl = 'http://fake.uri/?' + xhr.responseText;
  var showPrivateRepo = url.parse(fakeUrl,true).query['scope'] === 'repo';

  console.log('got auth token: ');
  console.log(url.parse(fakeUrl, true));

  res.redirect('/?private_repo='+showPrivateRepo + '#' + url.parse(fakeUrl, true).query['access_token']);
});

require('./lib/priorization')(app, {url: configServer.redisUrl});

port = process.env.PORT || 3000;
app.listen(port);
console.log('Server started. Running on port', port);
<commit_msg> removing console.logs in authentication<commit_after>var express = require('express');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var url = require('url');
var sass = require('node-sass');
var app = express();
var _ = require('underscore');
var configServer = require('./config/server.js');
var configClient = require('./config/client.js');

app.use(sass.middleware({
  src: __dirname + '/app',
  debug: true
}));

app.use(express.static('app'));

var bodyParser = require('body-parser');
app.use( bodyParser.json() );

app.get('/config', function (req, res) {
  res.send(configClient);
});

app.get('/request_code', function (req, res) {
  if(req.query.requestPrivateRepositories){
    res.redirect('https://github.com/login/oauth/authorize?client_id=' + configServer.clientId + '&scope=repo');
  } else {
    res.redirect('https://github.com/login/oauth/authorize?client_id=' + configServer.clientId + '&scope=public_repo');
  }
});

app.get('/request_auth_token', function (req, res) {
  var getAuthTokenUrl = 'https://github.com/login/oauth/access_token?' +
    'client_id=' + configServer.clientId +
    '&client_secret=' + configServer.clientSecret +
    '&code=' + req.query.code;

  xhr = new XMLHttpRequest();
  xhr.open('POST', getAuthTokenUrl, false);
  xhr.send();

  var fakeUrl = 'http://fake.uri/?' + xhr.responseText;
  var showPrivateRepo = url.parse(fakeUrl,true).query['scope'] === 'repo';

  res.redirect('/?private_repo='+showPrivateRepo + '#' + url.parse(fakeUrl, true).query['access_token']);
});

require('./lib/priorization')(app, {url: configServer.redisUrl});

port = process.env.PORT || 3000;
app.listen(port);
console.log('Server started. Running on port', port);
<|endoftext|>


<commit_before>/* Copyright (c) 2014 Jonathan Herman - MIT License */
/* http://github.com/jdh11235/lightswitch */

//defaults for localStorage:

var Defaults = {

	click_radius: 1,

	board_width: 30,
	board_height: 30,

	scramble_iterations: 30

};

//classes, organized alphabetically:

var Game = {

	createBoard: function (width, height) {

	},

	newGame: function () {

	},

	switchTile: function (x, y) {

	}

};

var UI = {

	renderGameboard: function () {

	}

};

var Util = {

	initDefaults: function () {
		for (key in Defaults) {
			if (!localStorage[key]) {
				localStorage[key] = Defaults[key];
			}
		}
	},

	init: function () {
		Util.initDefaults();
	}

};

//init hook:

window.onload = Util.init;
<commit_msg>initDefaults => setupDefaults<commit_after>/* Copyright (c) 2014 Jonathan Herman - MIT License */
/* http://github.com/jdh11235/lightswitch */

//defaults for localStorage:

var Defaults = {

	click_radius: 1,

	board_width: 30,
	board_height: 30,

	scramble_iterations: 30

};

//classes, organized alphabetically:

var Game = {

	createBoard: function (width, height) {

	},

	newGame: function () {

	},

	switchTile: function (x, y) {

	}

};

var UI = {

	renderGameboard: function () {

	}

};

var Util = {

	init: function () {
		Util.setupDefaults();
	},

	setupDefaults: function () {
		for (key in Defaults) {
			if (!localStorage[key]) {
				localStorage[key] = Defaults[key];
			}
		}
	}

};

//init hook:

window.onload = Util.init;
<|endoftext|>


<commit_before>/**
 * raml-mock-server
 *
 * @type {[type]}
 */
var program             = require('commander'),
    path                = require('path'),
    pkg                 = require( path.join(__dirname, 'package.json') );
    raml                = require('raml-parser'),
    fs                  = require('fs'),
    stripJsonComments   = require('strip-json-comments'),
    express             = require('express'),
    randomWorld         = require('random-world'),
    _                   = require('underscore'),
    cors                = require('cors'),
    bodyParser          = require('body-parser'),
    url                 = require('url'),
    os                  = require('os'),
    // no caching of the data (default is to serve random payloads every time)
    cacheLib            = require(path.resolve(path.join(__dirname, 'lib/cache'))),
    cacheWriteDir       = path.resolve(path.join(__dirname, 'cache')),
    cache               = false,
    cacheId             = false,
    // response latency
    latency             = 0,
    // set up the app
    app                 = express(),
    // port should be set on the CLI but will default to 3000
    port                = 3000,
    responses           = {
        contentTypes: {
            json: 'application/json',
            mock: 'application/mock'
        },
        statuses: {
            OK:         "200",
            NotFound:   "404",
            BadRequest: "400",
            NoContent:  "204",
            Conflict:   "409"
        }
    };

/**
 * Listen for commandline options
 *
 * If everything provided, start the service
 */
program
    .version(pkg.version)
    .description('Starts a standalone server for mocking data on endpoints defined by RAML files.')
    .option('-p, --port <port>', 'Port on which to listen to (defaults to 3000)', parseInt)
    .option('-s, --source <source>', 'Path to the source RAML file')
    .option('-c, --cacheid <cache id>', 'Identifier to use for caching purposes - off by default (data will be random on each request)')
    .option('-e, --latency <latency>', 'Emulate latency on the request (milliseconds)')
    .parse(process.argv);

if (typeof program.port === 'undefined') {
   console.error('No port provided.');
   program.outputHelp();
   process.exit(1);
}

if (typeof program.source === 'undefined') {
   console.error('No source map provided.');
   program.outputHelp();
   process.exit(1);
}

if (typeof program.cacheid !== 'undefined') {
    cacheId = program.cacheid;
    cache = cacheLib(cacheWriteDir, cacheId);
}

if (typeof program.latency !== 'undefined') {
    latency = program.latency;
}

// set port
port = program.port;

// need to set CORs up
cors({
    credentials: true,
    origin: true
});

function makeEndpoints (data) {

    var resources = data.resources,
        traits = data.traits;

    function setupResources (resourceCollection, prefix) {

        resourceCollection.forEach(function (resource) {

            var hasTraits   = resources.is,
                route       = prefix + resource.relativeUri,
                httpVerb    = '';

            if (resource.methods) {

                // loop over the available methods
                resource.methods.forEach(function(method) {

                    route       = route.replace(/\{/, ':').replace('\}', '');
                    httpVerb    = method.method.toLowerCase();

                    // console.log("Setting up route via [%s] for %s", httpVerb.toUpperCase(), route);

                    try {

                        /**
                         * introduces simulated network latency
                         *
                         * @param  {[type]}   req  [description]
                         * @param  {[type]}   res  [description]
                         * @param  {Function} next [description]
                         * @return {[type]}        [description]
                         */
                        function emulateNetworkLatency (req, res, next) {
                            if (latency > 0) {
                                console.log("Emulating %sms latency on [%s][route] %sms", latency, httpVerb, route);
                            }
                            setTimeout(next, latency);
                        }

                        app[httpVerb](route, emulateNetworkLatency, function (req, res) {

                            console.log('[%s]', req.method.toUpperCase(), route);

                            var requestParams   = _.defaults(req.query, req.body),

                                // the parameters accepted by the service
                                queryParameters = _.keys(method.queryParameters),

                                // default code is 200
                                responsePayload = null,
                                responseCode    = responses.statuses.OK,
                                responseType    = responses.contentTypes.json,

                                // define if the cache should be enforced
                                ignoreCache     = req.headers['cache-control'] === 'no-cache',

                                cacheRoute      = url.parse(req.url).pathname,

                                // default headers
                                headers = {
                                    'X-RAML-Mocker':    "Eh up!",
                                    'X-RAML-CacheId':   cacheId,
                                    'Content-type':     responseType
                                },

                                // mock data
                                mock = {
                                    MockingData: false,
                                    Status: "Please add application/mock to the RAML responses array for this method."
                                };

                            // remove any params that aren't explicitly defined by the service
                            requestParams = _.pick(requestParams, queryParameters);

                            switch (req.method.toUpperCase()) {

                                case 'GET':

                                    responseCode = responses.statuses.OK;
                                    queryParameters = method.queryParameters;

                                    // console.log("got a GET [%s]", responseCode, requestParams);

                                    // attempt to get the mocking data
                                    if (method.responses[responseCode].body[responses.contentTypes.mock]) {

                                        //
                                        if (cacheId && cache.has(cacheRoute) && !ignoreCache) {
                                            mock = cache.get(cacheRoute);
                                        } else {

                                            mock = method
                                                .responses[responses.statuses.OK]
                                                .body[responses.contentTypes.mock]
                                                .example;

                                            // generates a mock object using the random-world lib
                                            mock = randomWorld.fromMock(randomWorld, mock);

                                            if (cacheId && !ignoreCache) {
                                                try {
                                                    cache.set(cacheRoute, mock);
                                                } catch (e) {
                                                    console.error('Error caching data %s', e);
                                                }
                                            }
                                        }

                                    // default to the json response - this is probably not very useful
                                    } else if (method.responses[responses.statuses.OK].body[responses.contentTypes.json]) {

                                        mock = stripJsonComments(
                                            method.responses[responses.statuses.OK].body[responses.contentTypes.json]
                                        );
                                    }

                                    // attempt to get the appropriate headers from the RAML
                                    if (method.responses[responses.statuses.OK].headers) {

                                        var pages = 1,
                                            page = 1,
                                            limit = 10,
                                            total;

                                        // merge the headers from the RAML spec with the defaults
                                        headers = _.defaults(
                                            headers,
                                            method.responses[responses.statuses.OK].headers
                                        );

                                        // because they're raml objects, we need to assign a real value to the header instead
                                        // of a native object
                                        _.each(headers, function(header, val) {

                                            if (requestParams.page) {
                                                page = requestParams.page;
                                            }

                                            if (requestParams.limit) {
                                                limit = requestParams.limit;
                                            }

                                            if (limit && page) {
                                                pages = mock.length / limit;
                                            }

                                            // try adding the example, if set
                                            if (_.isObject(header)) {
                                                headers[val] = val.example || 0;
                                            }

                                            switch (val.toLowerCase()) {
                                                case 'x-pagination-total-pages':
                                                    headers[val] = pages;
                                                    break;
                                                case 'x-pagination-current-page':
                                                    headers[val] = page;
                                                    break;
                                                case 'x-pagination-per-page':
                                                    headers[val] = limit;
                                                    break;
                                                case 'x-pagination-total-entries':
                                                    headers[val] = mock.length;
                                                    break;
                                            }
                                        });
                                    }

                                    // limit the response data
                                    if (_.has(requestParams, 'limit') && _.isArray(mock)) {

                                        var p = +(page) - 1,
                                            limit = +limit;
                                            start = +(p * limit),
                                            end = (start + limit);

                                        // console.log("slicing data... page: %s limit: %s = slice(%s, %s)", page, limit, start, end);
                                        mock = mock.slice(start, end);
                                    }

                                    responsePayload = JSON.stringify(mock);

                                    break;
                                case 'POST':
                                    // console.log("got a POST");
                                    responseCode = responses.statuses.OK;
                                    break;
                                case 'PATCH':

                                    console.log("got a PATCH", requestParams, req.url);

                                    responseCode = responses.statuses.NoContent;

                                    // no content type
                                    delete headers['Content-type'];

                                    // test cache for the data
                                    if (cache.has(cacheRoute)) {

                                        mock = cache.get(cacheRoute);

                                        if (!_.isObject(mock)) {
                                            mock = JSON.parse(mock);
                                        }

                                        // update the data
                                        mock = _.extend(mock, requestParams);

                                        // reset the data
                                        cache.set(cacheRoute, mock);
                                    } else {
                                        responseCode = responses.statuses.NotFound;
                                    }

                                    break;
                                case 'DELETE':
                                    // console.log("got a DELETE");
                                    responseCode = responses.statuses.NoContent;

                                    // test cache for the data
                                    if (cache.has(cacheRoute)) {

                                        // reset the data
                                        cache.remove(cacheRoute);

                                        // no content type
                                        delete headers['Content-type'];
                                    } else {
                                        responseCode = responses.statuses.NotFound;
                                    }

                                    break;
                                case 'PUT':
                                    // console.log("got a PUT");
                                    responseCode = responses.statuses.OK;
                                    delete headers['Content-type'];
                                    break;
                            }

                            // set headers for the response
                            res.set(headers);
                            res.writeHead(responseCode);
                            res.end(responsePayload);
                        });

                    } catch (e) {
                        console.error('Error setting up route %s', e);
                    }
                });
            }

            if (resource.resources) {
                setupResources(resource.resources, prefix + resource.relativeUri);
            }
        });
    }

    setupResources(resources, '');
}

raml.loadFile(program.source).then(function(data) {
    makeEndpoints(data);
}, function(error) {
    console.log('Error parsing RAML file:', error);
});

// start server
var server = app.listen(port, function () {

    // remove annoying header
    app.disable('x-powered-by');

    // grab any params in PUT/PATCH/POST requests
    app.use(bodyParser.urlencoded({ extended: true }));

    // enable CORs requests
    app.use(cors());

    // debug
    var networkInterfaces = os.networkInterfaces(),
        host =  _.find(networkInterfaces['en0'], function(iface){
                    return iface.family === 'IPv4';
                }).address;

    console.log('RAML mocker listening at http://%s:%s', host, port);
});<commit_msg>CORs tweak<commit_after>/**
 * raml-mock-server
 *
 * @type {[type]}
 */
var program             = require('commander'),
    path                = require('path'),
    pkg                 = require( path.join(__dirname, 'package.json') );
    raml                = require('raml-parser'),
    fs                  = require('fs'),
    stripJsonComments   = require('strip-json-comments'),
    express             = require('express'),
    randomWorld         = require('random-world'),
    _                   = require('underscore'),
    cors                = require('cors'),
    bodyParser          = require('body-parser'),
    url                 = require('url'),
    os                  = require('os'),
    // no caching of the data (default is to serve random payloads every time)
    cacheLib            = require(path.resolve(path.join(__dirname, 'lib/cache'))),
    cacheWriteDir       = path.resolve(path.join(__dirname, 'cache')),
    cache               = false,
    cacheId             = false,
    // response latency
    latency             = 0,
    //
    corsSetup           = {},
    // set up the app
    app                 = express(),
    // port should be set on the CLI but will default to 3000
    port                = 3000,
    responses           = {
        contentTypes: {
            json: 'application/json',
            mock: 'application/mock'
        },
        statuses: {
            OK:         "200",
            NotFound:   "404",
            BadRequest: "400",
            NoContent:  "204",
            Conflict:   "409"
        }
    };

/**
 * Listen for commandline options
 *
 * If everything provided, start the service
 */
program
    .version(pkg.version)
    .description('Starts a standalone server for mocking data on endpoints defined by RAML files.')
    .option('-h, --host <x-origin host name>', 'Allow x-origin requests to be handled by the CORs hander')
    .option('-p, --port <port>', 'Port on which to listen to (defaults to 3000)', parseInt)
    .option('-s, --source <source>', 'Path to the source RAML file')
    .option('-c, --cacheid <cache id>', 'Identifier to use for caching purposes - off by default (data will be random on each request)')
    .option('-e, --latency <latency>', 'Emulate latency on the request (milliseconds)')
    .parse(process.argv);

if (typeof program.port === 'undefined') {
   console.error('No port provided.');
   program.outputHelp();
   process.exit(1);
}

if (typeof program.host !== 'undefined') {
    corsSetup = {
        origin: program.host
    };
}

if (typeof program.source === 'undefined') {
   console.error('No source map provided.');
   program.outputHelp();
   process.exit(1);
}

if (typeof program.cacheid !== 'undefined') {
    cacheId = program.cacheid;
    cache = cacheLib(cacheWriteDir, cacheId);
}

if (typeof program.latency !== 'undefined') {
    latency = program.latency;
}

// set port
port = program.port;

// need to set CORs up
cors({
    credentials: true,
    origin: true
});

function makeEndpoints (data) {

    var resources = data.resources,
        traits = data.traits;

    function setupResources (resourceCollection, prefix) {

        resourceCollection.forEach(function (resource) {

            var hasTraits   = resources.is,
                route       = prefix + resource.relativeUri,
                httpVerb    = '';

            if (resource.methods) {

                // loop over the available methods
                resource.methods.forEach(function(method) {

                    route       = route.replace(/\{/, ':').replace('\}', '');
                    httpVerb    = method.method.toLowerCase();

                    // console.log("Setting up route via [%s] for %s", httpVerb.toUpperCase(), route);

                    try {

                        /**
                         * introduces simulated network latency
                         *
                         * @param  {[type]}   req  [description]
                         * @param  {[type]}   res  [description]
                         * @param  {Function} next [description]
                         * @return {[type]}        [description]
                         */
                        function emulateNetworkLatency (req, res, next) {
                            if (latency > 0) {
                                console.log("Emulating %sms latency on [%s][route] %sms", latency, httpVerb, route);
                            }
                            setTimeout(next, latency);
                        }

                        app[httpVerb](route, emulateNetworkLatency, function (req, res) {

                            console.log('[%s]', req.method.toUpperCase(), route);

                            var requestParams   = _.defaults(req.query, req.body),

                                // the parameters accepted by the service
                                queryParameters = _.keys(method.queryParameters),

                                // default code is 200
                                responsePayload = null,
                                responseCode    = responses.statuses.OK,
                                responseType    = responses.contentTypes.json,

                                // define if the cache should be enforced
                                ignoreCache     = req.headers['cache-control'] === 'no-cache',

                                cacheRoute      = url.parse(req.url).pathname,

                                // default headers
                                headers = {
                                    'X-RAML-Mocker':    "Eh up!",
                                    'X-RAML-CacheId':   cacheId,
                                    'Content-type':     responseType
                                },

                                // mock data
                                mock = {
                                    MockingData: false,
                                    Status: "Please add application/mock to the RAML responses array for this method."
                                };

                            // remove any params that aren't explicitly defined by the service
                            requestParams = _.pick(requestParams, queryParameters);

                            switch (req.method.toUpperCase()) {

                                case 'GET':

                                    responseCode = responses.statuses.OK;
                                    queryParameters = method.queryParameters;

                                    // console.log("got a GET [%s]", responseCode, requestParams);

                                    // attempt to get the mocking data
                                    if (method.responses[responseCode].body[responses.contentTypes.mock]) {

                                        //
                                        if (cacheId && cache.has(cacheRoute) && !ignoreCache) {
                                            mock = cache.get(cacheRoute);
                                        } else {

                                            mock = method
                                                .responses[responses.statuses.OK]
                                                .body[responses.contentTypes.mock]
                                                .example;

                                            // generates a mock object using the random-world lib
                                            mock = randomWorld.fromMock(randomWorld, mock);

                                            if (cacheId && !ignoreCache) {
                                                try {
                                                    cache.set(cacheRoute, mock);
                                                } catch (e) {
                                                    console.error('Error caching data %s', e);
                                                }
                                            }
                                        }

                                    // default to the json response - this is probably not very useful
                                    } else if (method.responses[responses.statuses.OK].body[responses.contentTypes.json]) {

                                        mock = stripJsonComments(
                                            method.responses[responses.statuses.OK].body[responses.contentTypes.json]
                                        );
                                    }

                                    // attempt to get the appropriate headers from the RAML
                                    if (method.responses[responses.statuses.OK].headers) {

                                        var pages = 1,
                                            page = 1,
                                            limit = 10,
                                            total;

                                        // merge the headers from the RAML spec with the defaults
                                        headers = _.defaults(
                                            headers,
                                            method.responses[responses.statuses.OK].headers
                                        );

                                        // because they're raml objects, we need to assign a real value to the header instead
                                        // of a native object
                                        _.each(headers, function(header, val) {

                                            if (requestParams.page) {
                                                page = requestParams.page;
                                            }

                                            if (requestParams.limit) {
                                                limit = requestParams.limit;
                                            }

                                            if (limit && page) {
                                                pages = mock.length / limit;
                                            }

                                            // try adding the example, if set
                                            if (_.isObject(header)) {
                                                headers[val] = val.example || 0;
                                            }

                                            switch (val.toLowerCase()) {
                                                case 'x-pagination-total-pages':
                                                    headers[val] = pages;
                                                    break;
                                                case 'x-pagination-current-page':
                                                    headers[val] = page;
                                                    break;
                                                case 'x-pagination-per-page':
                                                    headers[val] = limit;
                                                    break;
                                                case 'x-pagination-total-entries':
                                                    headers[val] = mock.length;
                                                    break;
                                            }
                                        });
                                    }

                                    // limit the response data
                                    if (_.has(requestParams, 'limit') && _.isArray(mock)) {

                                        var p = +(page) - 1,
                                            limit = +limit;
                                            start = +(p * limit),
                                            end = (start + limit);

                                        // console.log("slicing data... page: %s limit: %s = slice(%s, %s)", page, limit, start, end);
                                        mock = mock.slice(start, end);
                                    }

                                    responsePayload = JSON.stringify(mock);

                                    break;
                                case 'POST':
                                    // console.log("got a POST");
                                    responseCode = responses.statuses.OK;
                                    break;
                                case 'PATCH':

                                    console.log("got a PATCH", requestParams, req.url);

                                    responseCode = responses.statuses.NoContent;

                                    // no content type
                                    delete headers['Content-type'];

                                    // test cache for the data
                                    if (cache.has(cacheRoute)) {

                                        mock = cache.get(cacheRoute);

                                        if (!_.isObject(mock)) {
                                            mock = JSON.parse(mock);
                                        }

                                        // update the data
                                        mock = _.extend(mock, requestParams);

                                        // reset the data
                                        cache.set(cacheRoute, mock);
                                    } else {
                                        responseCode = responses.statuses.NotFound;
                                    }

                                    break;
                                case 'DELETE':
                                    // console.log("got a DELETE");
                                    responseCode = responses.statuses.NoContent;

                                    // test cache for the data
                                    if (cache.has(cacheRoute)) {

                                        // reset the data
                                        cache.remove(cacheRoute);

                                        // no content type
                                        delete headers['Content-type'];
                                    } else {
                                        responseCode = responses.statuses.NotFound;
                                    }

                                    break;
                                case 'PUT':
                                    // console.log("got a PUT");
                                    responseCode = responses.statuses.OK;
                                    delete headers['Content-type'];
                                    break;
                            }

                            // set headers for the response
                            res.set(headers);
                            res.writeHead(responseCode);
                            res.end(responsePayload);
                        });

                    } catch (e) {
                        console.error('Error setting up route %s', e);
                    }
                });
            }

            if (resource.resources) {
                setupResources(resource.resources, prefix + resource.relativeUri);
            }
        });
    }

    setupResources(resources, '');
}

raml.loadFile(program.source).then(function(data) {
    makeEndpoints(data);
}, function(error) {
    console.log('Error parsing RAML file:', error);
});

// start server
var server = app.listen(port, function () {

    // debug
    var networkInterfaces = os.networkInterfaces(),
        host =  _.find(networkInterfaces['en0'], function(iface){
                    return iface.family === 'IPv4';
                }).address;

    // remove annoying header
    app.disable('x-powered-by');

    // grab any params in PUT/PATCH/POST requests
    app.use(bodyParser.urlencoded({ extended: true }));

    // enable CORs requests
    app.use(cors({origin: true, credentials: true}));

    console.log('RAML mocker listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express'),
http = require('http'),
passport = require('passport'),
util = require('util'),
path = require('path'),
FacebookStrategy = require('passport-facebook').Strategy,
config = require('./config.js'),
data = require('./lib/data.js');

var app = express();

app.configure(function () {
	app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'mustache');
    app.engine('mustache', require('hogan-middleware').__express);
	app.use(express.favicon(path.join(__dirname, 'public/favicon.png')));
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
	app.use(express.session({
			secret : config.sessionsecret
		}));
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler());
}
// passport
passport.use(new FacebookStrategy({
    clientID: config.facebookid,
    clientSecret: config.facebooksecret,
    callbackURL: "http://delta.dev.geeksoc.org/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    data.findOne({ facebookId: profile.id }, function (err, user) {
    if (err) return done(err);
      if (!user) return done(null, false, { message: "Please register." });
      return done(err, user);
      }
    );
  }

));

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  data.getDistinct(id, function(err, user) {
    done(err, user);
  });
});

app.get('/', function (req, res) {
res.render('index', {
		page : 'Main Page',
        theme : 'yeti',
		user : req.user
	});
});

// auth routes
app.get('/auth/facebook',
  passport.authenticate('facebook'));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

app.get('/users', function (req, res) {
  data.listAllPeople(function(e, results){
      res.send(results);
    });
  });

http.createServer(app).listen(app.get('port'), function () {
	console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>Start creation of User<commit_after>
/**
 * Module dependencies.
 */

var express = require('express'),
http = require('http'),
passport = require('passport'),
util = require('util'),
path = require('path'),
FacebookStrategy = require('passport-facebook').Strategy,
config = require('./config.js'),
data = require('./lib/data.js');

var app = express();

app.configure(function () {
	app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'mustache');
    app.engine('mustache', require('hogan-middleware').__express);
	app.use(express.favicon(path.join(__dirname, 'public/favicon.png')));
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
	app.use(express.session({
			secret : config.sessionsecret
		}));
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler());
}
// passport
passport.use(new FacebookStrategy({
    clientID: config.facebookid,
    clientSecret: config.facebooksecret,
    callbackURL: "http://delta.dev.geeksoc.org/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    data.findOne({ facebookId: profile.id }, function (err, user) {
    if (err) return done(err);
      if (!user) return generateUserFB(profile,done);
      return done(err, user);
      }
    );
  }

));

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  data.getDistinct(id, function(err, user) {
    done(err, user);
  });
});

app.get('/', function (req, res) {
res.render('index', {
		page : 'Main Page',
        theme : 'yeti',
		user : req.user
	});
});

// auth routes
app.get('/auth/facebook',
  passport.authenticate('facebook'));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

app.get('/users', function (req, res) {
  data.listAllPeople(function(e, results){
      res.send(results);
    });
  });

function generateUserFB(profile,done){
data.addPerson({ facebookId: profile.id });
data.findOne({ facebookId: profile.id }, function (err, user) {
    if (err) return done(err);
      if (!user) return done(null,false);
      return done(err, user);
      }
    );

}

http.createServer(app).listen(app.get('port'), function () {
	console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>var express = require('express');
var os = require('os');
var ip = require('ip');
var app = express();
var greeting = process.env.GREETING;
var who = process.env.WHO;
var fs = require("fs");
var namespace = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/namespace").toString();

function say_hello(){
    return greeting + " " + who + "! - I am Pod: " + os.hostname() + " - My IP: " + ip.address();
}

function get_namespace(){
    return "Project: " + namespace;
}

function read_file(){
    if (fs.existsSync('/etc/hello.conf')) {
    var file = fs.readFileSync("/etc/hello.conf").toString();}
    else {
    var file = "file not found";}
    return file;
}

app.get('/api/hello', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send(say_hello());
});

app.get('/api/file', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send(read_file());
});

app.get('/api/project', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send(get_namespace());
});

app.get('/', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send('/api/health
 /api/hello
 /api/file
 /api/project');
});

app.get('/api/health', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send("I'm ok");
});

var server = app.listen(8080, '0.0.0.0', function() {
    var host = server.address().address
    var port = server.address().port

    console.log("Hello service running at http://%s:%s", host, port)
});
<commit_msg>automated push<commit_after>var express = require('express');
var os = require('os');
var ip = require('ip');
var app = express();
var greeting = process.env.GREETING;
var who = process.env.WHO;
var fs = require("fs");
var namespace = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/namespace").toString();

function Xsay_hello(){
    return greeting + " " + who + "! - I am Pod: " + os.hostname() + " - My IP: " + ip.address();
}

function get_namespace(){
    return "Project: " + namespace;
}

function read_file(){
    if (fs.existsSync('/etc/hello.conf')) {
    var file = fs.readFileSync("/etc/hello.conf").toString();}
    else {
    var file = "file not found";}
    return file;
}

app.get('/api/hello', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send(say_hello());
});

app.get('/api/file', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send(read_file());
});

app.get('/api/project', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send(get_namespace());
});

app.get('/', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send('/api/health
 /api/hello
 /api/file
 /api/project');
});

app.get('/api/health', function(req, resp) {
    resp.set('Access-Control-Allow-Origin', '*');
    resp.send("I'm ok");
});

var server = app.listen(8080, '0.0.0.0', function() {
    var host = server.address().address
    var port = server.address().port

    console.log("Hello service running at http://%s:%s", host, port)
});
<|endoftext|>


<commit_before>
/*
* This file serves as an example of how you can use flatsheet as a dependency
* in another project. This is useful in production so you can install
* flatsheet using npm, and pull in the latest version of flatsheet using npm
* instead of pulling and merging changes via git.
*/

var server = require('./lib/index')({
  site: {
    title: 'flatsheet',
    email: 'hi@example.com',
    url: 'http://127.0.0.1:3333',
    contact: 'your full name'
  }
});

server.listen();<commit_msg>Serialize server app to remove race condition for db instantiation<commit_after>
/*
* This file serves as an example of how you can use flatsheet as a dependency
* in another project. This is useful in production so you can install
* flatsheet using npm, and pull in the latest version of flatsheet using npm
* instead of pulling and merging changes via git.
*/

var server = require('./lib/index')({
  site: {
    title: 'flatsheet',
    email: 'hi@example.com',
    url: 'http://127.0.0.1:3333',
    contact: 'your full name'
  }
}, function() {
  server.listen();
});
<|endoftext|>