<commit_before>(function() {

var xrefsComponent = {
    bindings: {
        upi: '<',
        taxid: '<?'
    },
    controller: ['$http', '$interpolate', '$timeout', function($http, $interpolate, $timeout) {
        var ctrl = this;

        ctrl.$onInit = function() {
            $http.get($interpolate('/api/v1/rna/{{upi}}/xrefs')({upi: ctrl.upi}), {timeout: 5000}).then(
                function(response) {
                    // set ctrl.xrefs (filtering by taxid, if given)
                    if (ctrl.taxid) {
                        ctrl.xrefs = response.data.results;
                    }
                    else {
                        ctrl.xrefs = _.filter(response.data.results, function(result) {
                            return result.taxid == ctrl.taxid;
                        });
                    }

                    // ensure that xrefs data is rendered into the DOM
                    // before initializing DataTables
                    $timeout(function() {
                        var table = $("#annotations-table").DataTable({
                            "columnDefs": [
                                { targets: [0, 1, 2], visible: true },
                                { targets: [3, 4, 5], visible: false}
                            ], // hide columns, but keep them sortable
                            "autoWidth": true, // pre-recalculate column widths
                            "dom": "ftpil", // filter, table, pagination, information, length
                            //"paginationType": "bootstrap", // requires dataTables.bootstrap.js
                            "deferRender": false, // defer rendering until necessary
                            "language": {
                                "search": "", // don't display the "Search:" bit
                                "info": "_START_-_END_ of _TOTAL_", // change the informational text
                                "paginate": {
                                    "next": "",
                                    "previous": "",
                                }
                            },
                            "order": [[ 5, "desc" ]], // prioritize entries with genomic coordinates
                            "lengthMenu": [[5, 10, 20, 50, -1], [5, 10, 20, 50, "All"]],
                            "initComplete": function(settings, json) {
                                console.log("init complete");
                            }
                        });
                    });

                },
                function(response) {
                    // TODO: display an error message in template!
                }
            );
        }
    }],
    templateUrl: '/static/js/sequence-xrefs.html'
};

var taxonomyComponent = {
    bindings: {
        upi: '<',
        taxid: '<?'
    },
    controller: ['$http', '$interpolate',  function($http, $interpolate) {
        var ctrl = this;

        ctrl.$onInit = function() {
            var d3_species_tree = $('#d3-species-tree');

            if (!document.createElement('svg').getAttributeNS) {
                d3_species_tree.html('Your browser does not support SVG');
            }
            else {
                $http.get($interpolate("/rna/{{upi}}/lineage")({ upi: ctrl.upi })).then(
                    function(response) {
                        ctrl.response = response;
                        d3SpeciesTree(response.data, ctrl.upi, '#d3-species-tree');
                    },
                    function(response) {
                        ctrl.response = response;
                    }
                )
            }
        };
    }],
    template: '
' +
              '
' +
              '        Loading taxonomic tree...' +
              '
' +
              '
= 400" class="alert alert-danger fade">' +
              '        Sorry, there was a problem loading the data. Please try again and contact us if the problem persists.' +
              '
' +
              '
'
};

var publicationResourceFactory = function($resource) {
    return $resource(
        '/api/v1/rna/:upi/publications?page_size=:page',
        {upi: '@upi', page: '@page'},
        {
            get: {timeout: 5000, isArray: false}
        }
    );
};
publicationResourceFactory.$inject = ['$resource'];

var publicationsComponent = {
    bindings: {
        upi: '<',
        taxid: '<?'
    },
    controller: ['publicationResource', '$http', '$interpolate', function(publicationResource, $http, $interpolate) {
        var ctrl = this;

        ctrl.$onInit = function() {
            ctrl.abstracts = {};
            ctrl.publications = ctrl.fetchPublications(25);
        };

        /**
         * Asynchronously downloads <pageSize> (e.g. 25) publications
         * on this sequences and stores in ctrl.publications.
         *
         * @param {int} [25] pageSize - how many publications to load
         * @returns {publicationResource promise} - Array-like of publications
         */
        ctrl.fetchPublications = function(pageSize) {
            pageSize = pageSize || 25;

            return publicationResource.get(
                { upi: this.upi, page_size: pageSize },
                function(publications) {
                    // retrieve corresponding abstracts
                    for (var i=0; i < publications.results.length; i++) {
                        var pubmed_id = publications.results[i].pubmed_id;
                        ctrl.fetchAbstract(pubmed_id);
                    }
                }
            );
        };

        /**
         * Asynchronously downloads abstract for paper with given
         * pubmed_id (if available) and adds it to ctrl.abstracts.
         * Due to ugly JSONP syntax, we use raw $http instead of
         * resources here.
         *
         * @param {int|null|undefined} pubmed_id - paper's PubMed id
         * @return {HttpPromise|null}
         */
        ctrl.fetchAbstract = function(pubmed_id) {
            if (pubmed_id) {
                return $http.jsonp(
                    $interpolate('http://www.ebi.ac.uk/europepmc/webservices/rest/search?query=ext_id:{{ pubmed_id }}&format=json&resulttype=core')({pubmed_id: pubmed_id})
                ).then(
                    function(response) {
                        ctrl.abstracts[pubmed_id] = response.data.resultList.result[0].abstractText;
                    },
                    function(response) {
                        ctrl.abstracts[pubmed_id] = "Failed to download abstract";
                    }
                );
            }
            else {
                ctrl.abstracts[pubmed_id] = "Abstract is not available";
                return null;
            }
        };

        ctrl.loadMore = function(pageSize) {
            pageSize = pageSize || 25;
            var newPageSize = ctrl.publications.data.length + pageSize;
            ctrl.publications = fetchPublications(newPageSize);
        };
    }],
    template: '
' +
              '
Publications {{ $ctrl.publications.count }} total
' +
              '
' +
              '
' +
              '
' +
              '                {{ publication.title }}' +
              '
' +
              '                ' +
              '                    {{ author }}{{ $last ? "" : ", " }}' +
              '
' +
              '                    {{ publication.publication }}' +
              '                    ' +
              '                        Pubmed' +
              '                        Full text' +
              '                        <button class="btn btn-xs btn-default abstract-btn abstract-control" ng-click="abstractVisible = !abstractVisible">Hide abstractShow abstract</button>' +
              '
{{ $ctrl.abstracts[publication.pubmed_id] }}
' +
              '                    ' +
              '
' +
              '                   Find other sequences from this reference' +
              '                ' +
              '
' +
              '
' +
              '
' +
              '    <div ng-if="$ctrl.publications.count < $ctrl.publications.total" class="col-md-8">' +
              '        Displaying {{ $ctrl.publication.count }} of {{ $ctrl.publications.total }} publications' +
              '
' +
              '        <button class="btn btn-default btn-large" id="load-more-publications" ng-click="$ctrl.loadMore">Load more</button>' +
              '
' +
              '
' +
              '
' +
              '            ' +
              '            Loading publications...' +
              '
' +
              '    ' +
              '
' +
              '
'
};

var rnaSequenceController = function($scope, $location, $http, $interpolate, DTOptionsBuilder, DTColumnBuilder) {
    // Take upi and taxid from url. Note that $location.path() always starts with slash
    $scope.upi = $location.path().split('/')[2];
    $scope.taxid = $location.path().split('/')[3]; // TODO: this might not exist!

    // var xrefsUrl;
    // if ($scope.taxid !== undefined) {
    //     xrefsUrl = $interpolate('/rna/{{upi}}/xrefs/{{taxid}}')({ upi: $scope.upi, taxid: $scope.taxid });
    // } else {
    //     xrefsUrl = $interpolate('/rna/{{upi}}/xrefs')({ upi: $scope.upi});
    // }
    //
    // $scope.xrefs = $http.get(xrefsUrl).then(
    //     function(response) {
    //         $("#annotations-table").html(response.data);
    //         $("#annotations-table").DataTable({
    //             "columns": [null, null, null, {"bVisible": false}, {"bVisible": false}, {"bVisible": false}], // hide columns, but keep them sortable
    //             "autoWidth": true, // pre-recalculate column widths
    //             "dom": "ftpil", // filter, table, pagination, information, length
    //             //"paginationType": "bootstrap", // requires dataTables.bootstrap.js
    //             "deferRender": true, // defer rendering until necessary
    //             "language": {
    //                 "search": "", // don't display the "Search:" bit
    //                 "info": "_START_-_END_ of _TOTAL_", // change the informational text
    //                 "paginate": {
    //                     "next": "",
    //                     "previous": "",
    //                 }
    //             },
    //             "order": [[ 5, "desc" ]], // prioritize entries with genomic coordinates
    //             "lengthMenu": [[5, 10, 20, 50, -1], [5, 10, 20, 50, "All"]],
    //             "initComplete": function(settings, json) {
    //                 console.log("init complete");
    //             }
    //         });
    //         $scope.enableGenomicFeatures = response.data.indexOf('View genomic location') > 0;
    //         activateLiteratureReferences();
    //     },
    //     function(response) {
    //         // handle error
    //     }
    // );

    // function activateLiteratureReferences() {
    //     $(document).on('click', '.literature-refs-retrieve', function() {
    //         var $this = $(this);
    //         var accession = $this.data('accession');
    //         var target = $this.siblings('.literature-refs-content');
    //
    //         toggle_slider_icon();
    //         if (target.html().length > 0) {
    //             target.slideToggle();
    //         } else {
    //             $.get('/api/v1/accession/' + accession + '/citations', function(data) {
    //                 insert_content(data);
    //                 obj.activate_abstract_buttons($this.siblings().find('.abstract-btn'));
    //                 target.slideDown();
    //             });
    //         }
    //
    //         function toggle_slider_icon() {
    //             var up = '';
    //             var down = '';
    //             if ($this.html() === up) {
    //                 $this.html(down);
    //             } else {
    //                 $this.html(up);
    //             }
    //         }
    //
    //         function insert_content(data) {
    //             var source = $("#handlebars-literature-reference-tmpl").html();
    //             var template = Handlebars.compile(source);
    //             var wrapper = {
    //                 refs: data
    //             };
    //             target.html(template(wrapper));
    //         }
    //     });
    // }

};
rnaSequenceController.$inject = ['$scope', '$location', '$http', '$interpolate', 'DTOptionsBuilder', 'DTColumnBuilder'];

/**
 * Configuration function that allows this module to load data
 * from white-listed domains (required for JSONP from ebi.ac.uk).
 * @param $sceDelegateProvider
 */
var sceWhitelist = function($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        // Allow same origin resource loads.
        'self',
        // Allow loading from EBI
        'http://www.ebi.ac.uk/**'
    ]);
};
sceWhitelist.$inject = ['$sceDelegateProvider'];

angular.module("rnaSequence", ['datatables', 'ngResource', 'ngAnimate'])
    .config(sceWhitelist)
    .factory("publicationResource", publicationResourceFactory)
    .controller("rnaSequenceController", rnaSequenceController)
    .component("xrefsComponent", xrefsComponent)
    .component("taxonomyComponent", taxonomyComponent)
    .component("publicationsComponent", publicationsComponent);

})();
<commit_msg> #110 Abstracted-out a separate abstract component.<commit_after>(function() {

var xrefsComponent = {
    bindings: {
        upi: '<',
        taxid: '<?'
    },
    controller: ['$http', '$interpolate', '$timeout', function($http, $interpolate, $timeout) {
        var ctrl = this;

        ctrl.$onInit = function() {
            $http.get($interpolate('/api/v1/rna/{{upi}}/xrefs')({upi: ctrl.upi}), {timeout: 5000}).then(
                function(response) {
                    // set ctrl.xrefs (filtering by taxid, if given)
                    if (ctrl.taxid) {
                        ctrl.xrefs = response.data.results;
                    }
                    else {
                        ctrl.xrefs = _.filter(response.data.results, function(result) {
                            return result.taxid == ctrl.taxid;
                        });
                    }

                    // ensure that xrefs data is rendered into the DOM
                    // before initializing DataTables
                    $timeout(function() {
                        var table = $("#annotations-table").DataTable({
                            "columnDefs": [
                                { targets: [0, 1, 2], visible: true },
                                { targets: [3, 4, 5], visible: false}
                            ], // hide columns, but keep them sortable
                            "autoWidth": true, // pre-recalculate column widths
                            "dom": "ftpil", // filter, table, pagination, information, length
                            //"paginationType": "bootstrap", // requires dataTables.bootstrap.js
                            "deferRender": false, // defer rendering until necessary
                            "language": {
                                "search": "", // don't display the "Search:" bit
                                "info": "_START_-_END_ of _TOTAL_", // change the informational text
                                "paginate": {
                                    "next": "",
                                    "previous": "",
                                }
                            },
                            "order": [[ 5, "desc" ]], // prioritize entries with genomic coordinates
                            "lengthMenu": [[5, 10, 20, 50, -1], [5, 10, 20, 50, "All"]],
                            "initComplete": function(settings, json) {
                                console.log("init complete");
                            }
                        });
                    });

                },
                function(response) {
                    // TODO: display an error message in template!
                }
            );
        }
    }],
    templateUrl: '/static/js/sequence-xrefs.html'
};

var taxonomyComponent = {
    bindings: {
        upi: '<',
        taxid: '<?'
    },
    controller: ['$http', '$interpolate',  function($http, $interpolate) {
        var ctrl = this;

        ctrl.$onInit = function() {
            var d3_species_tree = $('#d3-species-tree');

            if (!document.createElement('svg').getAttributeNS) {
                d3_species_tree.html('Your browser does not support SVG');
            }
            else {
                $http.get($interpolate("/rna/{{upi}}/lineage")({ upi: ctrl.upi })).then(
                    function(response) {
                        ctrl.response = response;
                        d3SpeciesTree(response.data, ctrl.upi, '#d3-species-tree');
                    },
                    function(response) {
                        ctrl.response = response;
                    }
                )
            }
        };
    }],
    template: '
' +
              '
' +
              '        Loading taxonomic tree...' +
              '
' +
              '
= 400" class="alert alert-danger fade">' +
              '        Sorry, there was a problem loading the data. Please try again and contact us if the problem persists.' +
              '
' +
              '
'
};

var abstractComponent = {
    bindings: {
        pubmed_id: '<'
    },
    require: {
        parent: '^publicationsComponent'
    },
    controller: ['$http', '$interpolate', function($http, $interpolate) {
        var ctrl = this;

        ctrl.$onChanges = function(changes) {
            console.log(changes);
            ctrl.fetchAbstract(changes.pubmed_id);
        };

        /**
         * Asynchronously downloads abstract for paper with given
         * pubmed_id (if available) and adds it to ctrl.abstracts.
         * Due to ugly JSONP syntax, we use raw $http instead of
         * resources here.
         *
         * @param {int|null|undefined} pubmed_id - paper's PubMed id
         * @return {HttpPromise|null}
         */
        ctrl.fetchAbstract = function(pubmed_id) {
            if (pubmed_id) {
                return $http.jsonp(
                    $interpolate('http://www.ebi.ac.uk/europepmc/webservices/rest/search?query=ext_id:{{ pubmed_id }}&format=json&resulttype=core')({pubmed_id: pubmed_id})
                ).then(
                    function(response) {
                        ctrl.abstract = response.data.resultList.result[0].abstractText;
                    },
                    function(response) {
                        ctrl.abstract = "Failed to download abstract";
                    }
                );
            }
            else {
                ctrl.abstract = "Abstract is not available";
                return null;
            }
        };

    }],
    template: '<button class="btn btn-xs btn-default abstract-btn abstract-control" ng-click="abstractVisible = !abstractVisible">Hide abstractShow abstract</button>' +
              '
{{ $ctrl.abstracts[publication.pubmed_id] }}
'
};

var publicationResourceFactory = function($resource) {
    return $resource(
        '/api/v1/rna/:upi/publications?page_size=:page',
        {upi: '@upi', page: '@page'},
        {
            get: {timeout: 5000, isArray: false}
        }
    );
};
publicationResourceFactory.$inject = ['$resource'];

var publicationsComponent = {
    bindings: {
        upi: '<',
        taxid: '<?'
    },
    controller: ['publicationResource', function(publicationResource) {
        var ctrl = this;

        ctrl.$onInit = function() {
            ctrl.abstracts = {};
            ctrl.publications = ctrl.fetchPublications(25);
        };

        /**
         * Asynchronously downloads <pageSize> (e.g. 25) publications
         * on this sequences and stores in ctrl.publications.
         *
         * @param {int} [25] pageSize - how many publications to load
         * @returns {publicationResource promise} - Array-like of publications
         */
        ctrl.fetchPublications = function(pageSize) {
            pageSize = pageSize || 25;
            return publicationResource.get({ upi: this.upi, page_size: pageSize });
        };

        ctrl.loadMore = function(pageSize) {
            pageSize = pageSize || 25;
            var newPageSize = ctrl.publications.data.length + pageSize;
            ctrl.publications = fetchPublications(newPageSize);
        };
    }],
    template: '
' +
              '
Publications {{ $ctrl.publications.count }} total
' +
              '
' +
              '
' +
              '
' +
              '                {{ publication.title }}' +
              '
' +
              '                ' +
              '                    {{ author }}{{ $last ? "" : ", " }}' +
              '
' +
              '                    {{ publication.publication }}' +
              '                    ' +
              '                        Pubmed' +
              '                        Full text' +
              '                        <abstract-component pubmed_id="publication.pubmed_id"></abstract-component>' +
              '                    ' +
              '
' +
              '                   Find other sequences from this reference' +
              '                ' +
              '
' +
              '
' +
              '
' +
              '    <div ng-if="$ctrl.publications.count < $ctrl.publications.total" class="col-md-8">' +
              '        Displaying {{ $ctrl.publication.count }} of {{ $ctrl.publications.total }} publications' +
              '
' +
              '        <button class="btn btn-default btn-large" id="load-more-publications" ng-click="$ctrl.loadMore">Load more</button>' +
              '
' +
              '
' +
              '
' +
              '            ' +
              '            Loading publications...' +
              '
' +
              '    ' +
              '
' +
              '
'
};

var rnaSequenceController = function($scope, $location, $http, $interpolate, DTOptionsBuilder, DTColumnBuilder) {
    // Take upi and taxid from url. Note that $location.path() always starts with slash
    $scope.upi = $location.path().split('/')[2];
    $scope.taxid = $location.path().split('/')[3]; // TODO: this might not exist!

    // var xrefsUrl;
    // if ($scope.taxid !== undefined) {
    //     xrefsUrl = $interpolate('/rna/{{upi}}/xrefs/{{taxid}}')({ upi: $scope.upi, taxid: $scope.taxid });
    // } else {
    //     xrefsUrl = $interpolate('/rna/{{upi}}/xrefs')({ upi: $scope.upi});
    // }
    //
    // $scope.xrefs = $http.get(xrefsUrl).then(
    //     function(response) {
    //         $("#annotations-table").html(response.data);
    //         $("#annotations-table").DataTable({
    //             "columns": [null, null, null, {"bVisible": false}, {"bVisible": false}, {"bVisible": false}], // hide columns, but keep them sortable
    //             "autoWidth": true, // pre-recalculate column widths
    //             "dom": "ftpil", // filter, table, pagination, information, length
    //             //"paginationType": "bootstrap", // requires dataTables.bootstrap.js
    //             "deferRender": true, // defer rendering until necessary
    //             "language": {
    //                 "search": "", // don't display the "Search:" bit
    //                 "info": "_START_-_END_ of _TOTAL_", // change the informational text
    //                 "paginate": {
    //                     "next": "",
    //                     "previous": "",
    //                 }
    //             },
    //             "order": [[ 5, "desc" ]], // prioritize entries with genomic coordinates
    //             "lengthMenu": [[5, 10, 20, 50, -1], [5, 10, 20, 50, "All"]],
    //             "initComplete": function(settings, json) {
    //                 console.log("init complete");
    //             }
    //         });
    //         $scope.enableGenomicFeatures = response.data.indexOf('View genomic location') > 0;
    //         activateLiteratureReferences();
    //     },
    //     function(response) {
    //         // handle error
    //     }
    // );

    // function activateLiteratureReferences() {
    //     $(document).on('click', '.literature-refs-retrieve', function() {
    //         var $this = $(this);
    //         var accession = $this.data('accession');
    //         var target = $this.siblings('.literature-refs-content');
    //
    //         toggle_slider_icon();
    //         if (target.html().length > 0) {
    //             target.slideToggle();
    //         } else {
    //             $.get('/api/v1/accession/' + accession + '/citations', function(data) {
    //                 insert_content(data);
    //                 obj.activate_abstract_buttons($this.siblings().find('.abstract-btn'));
    //                 target.slideDown();
    //             });
    //         }
    //
    //         function toggle_slider_icon() {
    //             var up = '';
    //             var down = '';
    //             if ($this.html() === up) {
    //                 $this.html(down);
    //             } else {
    //                 $this.html(up);
    //             }
    //         }
    //
    //         function insert_content(data) {
    //             var source = $("#handlebars-literature-reference-tmpl").html();
    //             var template = Handlebars.compile(source);
    //             var wrapper = {
    //                 refs: data
    //             };
    //             target.html(template(wrapper));
    //         }
    //     });
    // }

};
rnaSequenceController.$inject = ['$scope', '$location', '$http', '$interpolate', 'DTOptionsBuilder', 'DTColumnBuilder'];

/**
 * Configuration function that allows this module to load data
 * from white-listed domains (required for JSONP from ebi.ac.uk).
 * @param $sceDelegateProvider
 */
var sceWhitelist = function($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        // Allow same origin resource loads.
        'self',
        // Allow loading from EBI
        'http://www.ebi.ac.uk/**'
    ]);
};
sceWhitelist.$inject = ['$sceDelegateProvider'];

angular.module("rnaSequence", ['datatables', 'ngResource', 'ngAnimate'])
    .config(sceWhitelist)
    .factory("publicationResource", publicationResourceFactory)
    .controller("rnaSequenceController", rnaSequenceController)
    .component("xrefsComponent", xrefsComponent)
    .component("taxonomyComponent", taxonomyComponent)
    .component("publicationsComponent", publicationsComponent)
    .component("abstractComponent", abstractComponent);

})();
<|endoftext|>


<commit_before>/**
#
#Copyright (c) 2011-2014 Razortooth Communications, LLC. All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification,
#are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#
#    * Redistributions in binary form must reproduce the above copyright notice,
#      this list of conditions and the following disclaimer in the documentation
#      and/or other materials provided with the distribution.
#
#    * Neither the name of Razortooth Communications, LLC, nor the names of its
#      contributors may be used to endorse or promote products derived from this
#      software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
#ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
#(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
#ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/

var JS =  require("js.js").JS,
	util = require("util"),
	url = require('url'),
  qs = require("querystring"),
  path = require("path"),
  fs = require("fs"),
  shareconfig = require('./shareconfig.json');

var INVALID_SHARE_PARAMETERS = "Missing required query parameters: apikey";
var INVALID_SHARE_REQUEST = "Missing required resource file in request";
var UNAUTHORIZED_USER = "You are not authorized to access this document";
var RESOURCE_PERMISSION_DENIED = "This resource is not available, permission denied";

var js = new JS();
js.CONFIG.DOCROOT = './static';
console.log(js.CONFIG);
js.create(js.address, js.CONFIG.HTTPWS_PORT);
js.listenHttpWS();
js.listenSocketIO(js.js_handler); // This is initially set to null, so it will fallback to use js.DEFAULT_JS_HANDLER

var starttime = (new Date()).getTime();

js.getterer("/share/[\\w\\.\\-]+", function(req, res) {
  var aquery = qs.parse(url.parse(req.url).query);
  console.log("aquery = " + JSON.stringify(aquery));
  var apikey = aquery.apikey;

  // Is there an api key?
  if (apikey === undefined || apikey === '') {
    console.log('Undefined API Key');
    res.writeHead(403, {  'Content-Type': 'text/plain',
                          'Content-Length': INVALID_SHARE_PARAMETERS.length
                  });
    res.write(INVALID_SHARE_PARAMETERS);
    res.end();
  } else {
    var aurl = url.parse(req.url);
    // Validate the API key in our ACL
    var adoc = aurl.pathname.substring(aurl.pathname.lastIndexOf('/') + 1);
    var assetpath = '/assets/' + adoc;
    console.log(aurl);
    console.log('adoc = ' + adoc);
    if (adoc === null || adoc === '') {
      console.log(INVALID_SHARE_REQUEST);
      res.writeHead(403, {  'Content-Type': 'text/plain',
                          'Content-Length': INVALID_SHARE_REQUEST.length
                  });
      res.write(INVALID_SHARE_REQUEST);
      res.end();
    }
    // Is the document under access control
    if (adoc in shareconfig.documents) {
      console.log('Document lookup succeeded for ' + JSON.stringify(shareconfig.documents[adoc]));
      // Is the api key in our ACL?
      if ((apikey in shareconfig.documents[adoc]) !== true) {
        console.log(UNAUTHORIZED_USER);
        res.writeHead(403, {  'Content-Type': 'text/plain',
                          'Content-Length': UNAUTHORIZED_USER.length
                  });
        res.write(UNAUTHORIZED_USER);
        res.end();
      } else {
        console.log("Lookup of acl user: " + apikey + " succeeded for " + adoc);
      }
    } else {
      console.log("failed to lookup " + adoc + " in ");
      console.log(shareconfig.documents);
      console.log(RESOURCE_PERMISSION_DENIED);
      res.writeHead(403, {  'Content-Type': 'text/plain',
                          'Content-Length': RESOURCE_PERMISSION_DENIED.length
                  });
      res.write(RESOURCE_PERMISSION_DENIED);
      res.end();
    }
    console.log("Getting share under path: " + url.parse(assetpath).pathname);
    return js.staticHandler("." + url.parse(assetpath).pathname)(req, res);
  }
});

js.get("/up", function(req, res) {
  res.simpleJSON(200, { "starttime": starttime});
});

<commit_msg>Change port to 80<commit_after>/**
#
#Copyright (c) 2011-2014 Razortooth Communications, LLC. All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification,
#are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#
#    * Redistributions in binary form must reproduce the above copyright notice,
#      this list of conditions and the following disclaimer in the documentation
#      and/or other materials provided with the distribution.
#
#    * Neither the name of Razortooth Communications, LLC, nor the names of its
#      contributors may be used to endorse or promote products derived from this
#      software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
#ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
#(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
#ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/

var JS =  require("js.js").JS,
	util = require("util"),
	url = require('url'),
  qs = require("querystring"),
  path = require("path"),
  fs = require("fs"),
  shareconfig = require('./shareconfig.json');

var INVALID_SHARE_PARAMETERS = "Missing required query parameters: apikey";
var INVALID_SHARE_REQUEST = "Missing required resource file in request";
var UNAUTHORIZED_USER = "You are not authorized to access this document";
var RESOURCE_PERMISSION_DENIED = "This resource is not available, permission denied";

var js = new JS();
js.CONFIG.DOCROOT = './static';
js.CONFIG.HTTPWS_PORT = 80;
console.log(js.CONFIG);
js.create(js.address, js.CONFIG.HTTPWS_PORT);
js.listenHttpWS();
js.listenSocketIO(js.js_handler); // This is initially set to null, so it will fallback to use js.DEFAULT_JS_HANDLER

var starttime = (new Date()).getTime();

js.getterer("/share/[\\w\\.\\-]+", function(req, res) {
  var aquery = qs.parse(url.parse(req.url).query);
  console.log("aquery = " + JSON.stringify(aquery));
  var apikey = aquery.apikey;

  // Is there an api key?
  if (apikey === undefined || apikey === '') {
    console.log('Undefined API Key');
    res.writeHead(403, {  'Content-Type': 'text/plain',
                          'Content-Length': INVALID_SHARE_PARAMETERS.length
                  });
    res.write(INVALID_SHARE_PARAMETERS);
    res.end();
  } else {
    var aurl = url.parse(req.url);
    // Validate the API key in our ACL
    var adoc = aurl.pathname.substring(aurl.pathname.lastIndexOf('/') + 1);
    var assetpath = '/assets/' + adoc;
    console.log(aurl);
    console.log('adoc = ' + adoc);
    if (adoc === null || adoc === '') {
      console.log(INVALID_SHARE_REQUEST);
      res.writeHead(403, {  'Content-Type': 'text/plain',
                          'Content-Length': INVALID_SHARE_REQUEST.length
                  });
      res.write(INVALID_SHARE_REQUEST);
      res.end();
    }
    // Is the document under access control
    if (adoc in shareconfig.documents) {
      console.log('Document lookup succeeded for ' + JSON.stringify(shareconfig.documents[adoc]));
      // Is the api key in our ACL?
      if ((apikey in shareconfig.documents[adoc]) !== true) {
        console.log(UNAUTHORIZED_USER);
        res.writeHead(403, {  'Content-Type': 'text/plain',
                          'Content-Length': UNAUTHORIZED_USER.length
                  });
        res.write(UNAUTHORIZED_USER);
        res.end();
      } else {
        console.log("Lookup of acl user: " + apikey + " succeeded for " + adoc);
      }
    } else {
      console.log("failed to lookup " + adoc + " in ");
      console.log(shareconfig.documents);
      console.log(RESOURCE_PERMISSION_DENIED);
      res.writeHead(403, {  'Content-Type': 'text/plain',
                          'Content-Length': RESOURCE_PERMISSION_DENIED.length
                  });
      res.write(RESOURCE_PERMISSION_DENIED);
      res.end();
    }
    console.log("Getting share under path: " + url.parse(assetpath).pathname);
    return js.staticHandler("." + url.parse(assetpath).pathname)(req, res);
  }
});

js.get("/up", function(req, res) {
  res.simpleJSON(200, { "starttime": starttime});
});

<|endoftext|>


<commit_before>'use strict'

var uuid = require('uuid')
var objectAssign = require('object-assign')
var express = require('./express-utils')
var debug = require('debug')('opbeat')
var Trace = require('./trace')

module.exports = Transaction

function Transaction (agent, name, type) {
  Object.defineProperty(this, 'name', {
    configurable: true,
    enumerable: true,
    get: function () {
      // Fall back to a somewhat useful name in case no _defaultName is set.
      // This might happen if res.writeHead wasn't called.
      return this._customName ||
        this._defaultName ||
        (this.req ? this.req.method + ' unknown route (unnamed)' : 'unnamed')
    },
    set: function (name) {
      if (this.ended) {
        debug('tried to set transaction.name on already ended transaction %o', {id: this.id})
        return
      }
      debug('setting transaction name %o', {id: this.id, name: name})
      this._customName = name
    }
  })

  Object.defineProperty(this, 'result', {
    configurable: true,
    enumerable: true,
    get: function () {
      return this._result
    },
    set: function (result) {
      if (this.ended) {
        debug('tried to set transaction.result on already ended transaction %o', {id: this.id})
        return
      }
      debug('setting transaction result %o', {id: this.id, result: result})
      this._result = result
    }
  })

  this.id = uuid.v4()
  this._defaultName = name || ''
  this._customName = ''
  this._context = null
  this.type = type || 'custom'
  this.result = 200
  this.traces = []
  this._buildTraces = []
  this.ended = false
  this._abortTime = 0
  this._agent = agent
  this._agent._instrumentation.currentTransaction = this

  debug('start transaction %o', {id: this.id, name: name, type: type})

  // A transaction should always have a root trace spanning the entire
  // transaction.
  this._rootTrace = new Trace(this)
  this._rootTrace.start('transaction', 'transaction')
  this._start = this._rootTrace._start
}

Transaction.prototype.setUserContext = function (context) {
  if (!context) return
  if (!this._context) this._context = {}
  this._context.user = objectAssign(this._context.user || {}, context)
}

Transaction.prototype.setExtraContext = function (context) {
  if (!context) return
  if (!this._context) this._context = {}
  this._context.extra = objectAssign(this._context.extra || {}, context)
}

Transaction.prototype.buildTrace = function () {
  if (this.ended) {
    debug('transaction already ended - cannot build new trace %o', {id: this.id})
    return null
  }

  var trace = new Trace(this)
  this._buildTraces.push(trace)
  return trace
}

Transaction.prototype.duration = function () {
  return this._rootTrace.duration()
}

Transaction.prototype.setDefaultName = function (name) {
  debug('setting default transaction name: %s %o', name, {id: this.id})
  this._defaultName = name
}

Transaction.prototype.setDefaultNameFromRequest = function () {
  var req = this.req
  var path = express.getPathFromRequest(req)

  if (!path) {
    debug('could not extract route name from request %o', {
      url: req.url,
      type: typeof path,
      null: path === null, // because typeof null === 'object'
      route: !!req.route,
      regex: req.route ? !!req.route.regexp : false,
      mountstack: req._opbeat_mountstack ? req._opbeat_mountstack.length : false,
      id: this.id
    })
    path = 'unknown route'
  }

  this.setDefaultName(req.method + ' ' + path)
}

Transaction.prototype.end = function () {
  if (this.ended) {
    debug('tried to call transaction.end() on already ended transaction %o', {id: this.id})
    return
  }

  if (!this._defaultName && this.req) this.setDefaultNameFromRequest()

  this._buildTraces.forEach(function (trace) {
    if (trace.ended || !trace.started) return
    trace.truncate()
  })

  this._rootTrace.end()
  this.ended = true

  var trans = this._agent._instrumentation.currentTransaction

  // These two edge-cases should normally not happen, but if the hooks into
  // Node.js doesn't work as intended it might. In that case we want to
  // gracefully handle it. That involves ignoring all traces under the given
  // transaction as they will most likely be incomplete. We still want to send
  // the transaction without any traces as it's still valuable data.
  if (!trans) {
    debug('WARNING: no currentTransaction found %o', {current: trans, traces: this.traces.length, id: this.id})
    this.traces = []
  } else if (trans !== this) {
    debug('WARNING: transaction is out of sync %o', {traces: this.traces.length, id: this.id, other: trans.id})
    this.traces = []
  }

  this._agent._instrumentation.addEndedTransaction(this)
  debug('ended transaction %o', {id: this.id, type: this.type, result: this.result, name: this.name})
}

Transaction.prototype._recordEndedTrace = function (trace) {
  if (this.ended) {
    debug('Can\'t record ended trace after parent transaction have ended - ignoring %o', {id: this.id, trace: trace.name})
    return
  }

  this.traces.push(trace)
}
<commit_msg>refactor(transaction): fix typo<commit_after>'use strict'

var uuid = require('uuid')
var objectAssign = require('object-assign')
var express = require('./express-utils')
var debug = require('debug')('opbeat')
var Trace = require('./trace')

module.exports = Transaction

function Transaction (agent, name, type) {
  Object.defineProperty(this, 'name', {
    configurable: true,
    enumerable: true,
    get: function () {
      // Fall back to a somewhat useful name in case no _defaultName is set.
      // This might happen if res.writeHead wasn't called.
      return this._customName ||
        this._defaultName ||
        (this.req ? this.req.method + ' unknown route (unnamed)' : 'unnamed')
    },
    set: function (name) {
      if (this.ended) {
        debug('tried to set transaction.name on already ended transaction %o', {id: this.id})
        return
      }
      debug('setting transaction name %o', {id: this.id, name: name})
      this._customName = name
    }
  })

  Object.defineProperty(this, 'result', {
    configurable: true,
    enumerable: true,
    get: function () {
      return this._result
    },
    set: function (result) {
      if (this.ended) {
        debug('tried to set transaction.result on already ended transaction %o', {id: this.id})
        return
      }
      debug('setting transaction result %o', {id: this.id, result: result})
      this._result = result
    }
  })

  this.id = uuid.v4()
  this._defaultName = name || ''
  this._customName = ''
  this._context = null
  this.type = type || 'custom'
  this.result = 200
  this.traces = []
  this._builtTraces = []
  this.ended = false
  this._abortTime = 0
  this._agent = agent
  this._agent._instrumentation.currentTransaction = this

  debug('start transaction %o', {id: this.id, name: name, type: type})

  // A transaction should always have a root trace spanning the entire
  // transaction.
  this._rootTrace = new Trace(this)
  this._rootTrace.start('transaction', 'transaction')
  this._start = this._rootTrace._start
}

Transaction.prototype.setUserContext = function (context) {
  if (!context) return
  if (!this._context) this._context = {}
  this._context.user = objectAssign(this._context.user || {}, context)
}

Transaction.prototype.setExtraContext = function (context) {
  if (!context) return
  if (!this._context) this._context = {}
  this._context.extra = objectAssign(this._context.extra || {}, context)
}

Transaction.prototype.buildTrace = function () {
  if (this.ended) {
    debug('transaction already ended - cannot build new trace %o', {id: this.id})
    return null
  }

  var trace = new Trace(this)
  this._builtTraces.push(trace)
  return trace
}

Transaction.prototype.duration = function () {
  return this._rootTrace.duration()
}

Transaction.prototype.setDefaultName = function (name) {
  debug('setting default transaction name: %s %o', name, {id: this.id})
  this._defaultName = name
}

Transaction.prototype.setDefaultNameFromRequest = function () {
  var req = this.req
  var path = express.getPathFromRequest(req)

  if (!path) {
    debug('could not extract route name from request %o', {
      url: req.url,
      type: typeof path,
      null: path === null, // because typeof null === 'object'
      route: !!req.route,
      regex: req.route ? !!req.route.regexp : false,
      mountstack: req._opbeat_mountstack ? req._opbeat_mountstack.length : false,
      id: this.id
    })
    path = 'unknown route'
  }

  this.setDefaultName(req.method + ' ' + path)
}

Transaction.prototype.end = function () {
  if (this.ended) {
    debug('tried to call transaction.end() on already ended transaction %o', {id: this.id})
    return
  }

  if (!this._defaultName && this.req) this.setDefaultNameFromRequest()

  this._builtTraces.forEach(function (trace) {
    if (trace.ended || !trace.started) return
    trace.truncate()
  })

  this._rootTrace.end()
  this.ended = true

  var trans = this._agent._instrumentation.currentTransaction

  // These two edge-cases should normally not happen, but if the hooks into
  // Node.js doesn't work as intended it might. In that case we want to
  // gracefully handle it. That involves ignoring all traces under the given
  // transaction as they will most likely be incomplete. We still want to send
  // the transaction without any traces as it's still valuable data.
  if (!trans) {
    debug('WARNING: no currentTransaction found %o', {current: trans, traces: this.traces.length, id: this.id})
    this.traces = []
  } else if (trans !== this) {
    debug('WARNING: transaction is out of sync %o', {traces: this.traces.length, id: this.id, other: trans.id})
    this.traces = []
  }

  this._agent._instrumentation.addEndedTransaction(this)
  debug('ended transaction %o', {id: this.id, type: this.type, result: this.result, name: this.name})
}

Transaction.prototype._recordEndedTrace = function (trace) {
  if (this.ended) {
    debug('Can\'t record ended trace after parent transaction have ended - ignoring %o', {id: this.id, trace: trace.name})
    return
  }

  this.traces.push(trace)
}
<|endoftext|>


<commit_before>var fs = require('fs');
var http = require('http');
var https = require('https');
var express = require('express');
var httpProxy = require('http-proxy');

// Create server

var app = express();
var server = http.createServer(app);

var oneDay = 86400000;

app.configure(function() {
    app.set('port', process.env.PORT || 2000);

    app.use(express.logger('dev'));
    app.use(express.compress());
    app.use('/app', express.static(__dirname + '/app', { maxAge: oneDay }));
    app.use('/public', express.static(__dirname + '/public', { maxAge: oneDay }));
    app.use('/favicon.ico', express.static(__dirname + '/favicon.ico', { maxAge: oneDay }));

    app.use(function (req, res, next) {
		if(req.url.match(/^\/activate=3Fkey/g)) {
	  		var fixedUrl = req.url.replace('/activate=3Fkey', '/activate?key');
	  		res.writeHead(302, { 'Location': fixedUrl });
			res.end();
	  	}
	  	else {
	  		next();
	  	}
	});
});

console.log("api-proto", app.get("api-proto"));
console.log("api-host",  app.get("api-host"));
console.log("api-port",  app.get("api-port"));

// Configure routes

var proxy = new httpProxy.RoutingProxy();

app.get   ('/app/*'   , function(req, res) { res.send('404', 404); } );
app.get   ('/public/*', function(req, res) { res.send('404', 404); } );

app.get   ('/api/*', function(req, res) { proxy.proxyRequest(req, res, { changeOrigin: true, host: 'api.cbd.int', https: true } ) } );
app.put   ('/api/*', function(req, res) { proxy.proxyRequest(req, res, { changeOrigin: true, host: 'api.cbd.int', https: true } ) } );
app.post  ('/api/*', function(req, res) { proxy.proxyRequest(req, res, { changeOrigin: true, host: 'api.cbd.int', https: true } ) } );
app.delete('/api/*', function(req, res) { proxy.proxyRequest(req, res, { changeOrigin: true, host: 'api.cbd.int', https: true } ) } );

// Configure index.html

app.get('/*', function(req, res) {

	if(req.headers.host=='accounts.cbd.int') {
		fs.readFile(__dirname + '/app/accounts.cbd.int.html', 'utf8', function (error, text) {
			res.send(text);
		});
	}
	else if(req.url.match(/^\/business/g)) {
		fs.readFile(__dirname + '/app/www.cbd.int-business.html', 'utf8', function (error, text) {
			res.send(text);
		});
	}
	else {
		fs.readFile(__dirname + '/app/index.html', 'utf8', function (error, text) {
			res.send(text);
		});
	}
});

// Start server

console.log('Server listening on port ' + app.get('port'));
server.listen(app.get('port'));<commit_msg>rollback<commit_after>var fs = require('fs');
var http = require('http');
var https = require('https');
var express = require('express');
var httpProxy = require('http-proxy');

// Create server

var app = express();
var server = http.createServer(app);

var oneDay = 86400000;

app.configure(function() {
    app.set('port', process.env.PORT || 2000);

    app.use(express.logger('dev'));
    app.use(express.compress());
    app.use('/app', express.static(__dirname + '/app', { maxAge: oneDay }));
    app.use('/public', express.static(__dirname + '/public', { maxAge: oneDay }));
    app.use('/favicon.ico', express.static(__dirname + '/favicon.ico', { maxAge: oneDay }));

    app.use(function (req, res, next) {
		if(req.url.match(/^\/activate=3Fkey/g)) {
	  		var fixedUrl = req.url.replace('/activate=3Fkey', '/activate?key');
	  		res.writeHead(302, { 'Location': fixedUrl });
			res.end();
	  	}
	  	else {
	  		next();
	  	}
	});
});

console.log("api-proto", app.get("api-proto"));
console.log("api-host",  app.get("api-host"));
console.log("api-port",  app.get("api-port"));

// Configure routes

var proxy = new httpProxy.RoutingProxy();

app.get   ('/app/*'   , function(req, res) { res.send('404', 404); } );
app.get   ('/public/*', function(req, res) { res.send('404', 404); } );

app.get   ('/api/*', function(req, res) { proxy.proxyRequest(req, res, { changeOrigin: true, host: 'api.cbd.int', port: 80,  } ) } );
app.put   ('/api/*', function(req, res) { proxy.proxyRequest(req, res, { changeOrigin: true, host: 'api.cbd.int', port: 80,  } ) } );
app.post  ('/api/*', function(req, res) { proxy.proxyRequest(req, res, { changeOrigin: true, host: 'api.cbd.int', port: 80,  } ) } );
app.delete('/api/*', function(req, res) { proxy.proxyRequest(req, res, { changeOrigin: true, host: 'api.cbd.int', port: 80,  } ) } );

// Configure index.html

app.get('/*', function(req, res) {

	if(req.headers.host=='accounts.cbd.int') {
		fs.readFile(__dirname + '/app/accounts.cbd.int.html', 'utf8', function (error, text) {
			res.send(text);
		});
	}
	else if(req.url.match(/^\/business/g)) {
		fs.readFile(__dirname + '/app/www.cbd.int-business.html', 'utf8', function (error, text) {
			res.send(text);
		});
	}
	else {
		fs.readFile(__dirname + '/app/index.html', 'utf8', function (error, text) {
			res.send(text);
		});
	}
});

// Start server

console.log('Server listening on port ' + app.get('port'));
server.listen(app.get('port'));<|endoftext|>


<commit_before>// Load our dependencies
var fs = require('fs');
var path = require('path');
var minstache = require('minstache');
var jsStringEscape = require('js-string-escape');
var convertSourceMap = require('convert-source-map');

// Resolve filepath to Karma's `context.html` and `debug.html`
// https://github.com/karma-runner/karma/blob/v1.3.0/lib/middleware/karma.js#L138-L157
// https://github.com/karma-runner/karma/blob/v1.3.0/lib/web-server.js#L33-L37
// https://github.com/karma-runner/karma/blob/v1.3.0/lib/middleware/common.js#L30-L70
var karmaWebServerFilepath = require.resolve('karma/lib/web-server');
var karmaStaticDirectoryFilepath = path.normalize(path.join(path.dirname(karmaWebServerFilepath), '/../static'));
// Example: /home/todd/github/karma-electron/node_modules/karma/static/context.html
var karmaDefaultContextFile = karmaStaticDirectoryFilepath + '/context.html';
var karmaDefaultDebugFile = karmaStaticDirectoryFilepath + '/debug.html';

// Load our template
// DEV: We minify to remove impact of line numbers
//   To reproduce this, make a test fail and remove minification
//   Notice how the error line goes from 10 to 30 =(
// DEV: We should be using a minifier but the mustache template prevents this
var templateStr = fs.readFileSync(__dirname + '/node-integration-iframe.mustache.js', 'utf8');
var minifiedTemplateStr = templateStr.replace(/\/\/[^\n]+/g, '\n').replace(/\n/g, '');
// DEV: We inject a newline after content to prevent `//` comments from breaking our closure
minifiedTemplateStr = minifiedTemplateStr.replace(/(content}})/, '$1\n');
var template = minstache.compile(minifiedTemplateStr);

// Define our framework to inject our `node-integration`
var $inject = ['config.basePath', 'config.customContextFile', 'config.customDebugFile'];
function createElectronPreprocessor(karmaBasePath, karmaCustomContextFile, karmaCustomDebugFile) {
  // Generate our preprocessor function
  function electronPreprocessor(content, file, done) {
    // Render our content without a source map
    var sourceMap = convertSourceMap.fromSource(content);
    var output = template({
      content: convertSourceMap.removeComments(content),
      dirname: jsStringEscape(path.dirname(file.originalPath)),
      filename: jsStringEscape(file.originalPath),
      karmaBasePath: jsStringEscape(karmaBasePath),
      karmaContextFile: jsStringEscape(karmaCustomContextFile || karmaDefaultContextFile),
      karmaDebugFile: jsStringEscape(karmaCustomDebugFile || karmaDefaultDebugFile),
      // TODO: Resolve loadScriptsViaRequire from config
      loadScriptsViaRequire: true,
      sep: jsStringEscape(path.sep)
    });

    // If there was a source map, add it back
    if (sourceMap) {
      output += '\n' + sourceMap.toComment();
    }

    // Callback with our content
    done(null, output);
  }

  // Return our preprocessor
  return electronPreprocessor;
}

// Define depenencies so our function can receive them
createElectronPreprocessor.$inject = $inject;

// Export our launcher
module.exports = {
  'preprocessor:electron': ['factory', createElectronPreprocessor]
};
<commit_msg>Fixed up handling of loadScriptsViaRequire<commit_after>// Load our dependencies
var fs = require('fs');
var path = require('path');
var minstache = require('minstache');
var jsStringEscape = require('js-string-escape');
var convertSourceMap = require('convert-source-map');

// Resolve filepath to Karma's `context.html` and `debug.html`
// https://github.com/karma-runner/karma/blob/v1.3.0/lib/middleware/karma.js#L138-L157
// https://github.com/karma-runner/karma/blob/v1.3.0/lib/web-server.js#L33-L37
// https://github.com/karma-runner/karma/blob/v1.3.0/lib/middleware/common.js#L30-L70
var karmaWebServerFilepath = require.resolve('karma/lib/web-server');
var karmaStaticDirectoryFilepath = path.normalize(path.join(path.dirname(karmaWebServerFilepath), '/../static'));
// Example: /home/todd/github/karma-electron/node_modules/karma/static/context.html
var karmaDefaultContextFile = karmaStaticDirectoryFilepath + '/context.html';
var karmaDefaultDebugFile = karmaStaticDirectoryFilepath + '/debug.html';

// Load our template
// DEV: We minify to remove impact of line numbers
//   To reproduce this, make a test fail and remove minification
//   Notice how the error line goes from 10 to 30 =(
// DEV: We should be using a minifier but the mustache template prevents this
var templateStr = fs.readFileSync(__dirname + '/node-integration-iframe.mustache.js', 'utf8');
var minifiedTemplateStr = templateStr.replace(/\/\/[^\n]+/g, '\n').replace(/\n/g, '');
// DEV: We inject a newline after content to prevent `//` comments from breaking our closure
minifiedTemplateStr = minifiedTemplateStr.replace(/(content}})/, '$1\n');
var template = minstache.compile(minifiedTemplateStr);

// Define our framework to inject our `node-integration`
var $inject = ['config.basePath', 'config.client.loadScriptsViaRequire',
   'config.customContextFile', 'config.customDebugFile'];
function createElectronPreprocessor(karmaBasePath, karmaLoadScriptsViaRequire,
    karmaCustomContextFile, karmaCustomDebugFile) {
  // Generate our preprocessor function
  function electronPreprocessor(content, file, done) {
    // Render our content without a source map
    var sourceMap = convertSourceMap.fromSource(content);
    var output = template({
      content: convertSourceMap.removeComments(content),
      dirname: jsStringEscape(path.dirname(file.originalPath)),
      filename: jsStringEscape(file.originalPath),
      karmaBasePath: jsStringEscape(karmaBasePath),
      karmaContextFile: jsStringEscape(karmaCustomContextFile || karmaDefaultContextFile),
      karmaDebugFile: jsStringEscape(karmaCustomDebugFile || karmaDefaultDebugFile),
      loadScriptsViaRequire: !!karmaLoadScriptsViaRequire,
      sep: jsStringEscape(path.sep)
    });

    // If there was a source map, add it back
    if (sourceMap) {
      output += '\n' + sourceMap.toComment();
    }

    // Callback with our content
    done(null, output);
  }

  // Return our preprocessor
  return electronPreprocessor;
}

// Define depenencies so our function can receive them
createElectronPreprocessor.$inject = $inject;

// Export our launcher
module.exports = {
  'preprocessor:electron': ['factory', createElectronPreprocessor]
};
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// Catch-all for any other responses not handled above
slapp.message(/^(what day is it\?)/i, ['mention', 'direct_message', 'direct_mention', 'ambient'], (msg) => {
  var now = new Date();
  var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  var day = days[ now.getDay() ];

  var returnMessage = "It's "+days[ now.getDay()];

  if(day == "Friday"){
    returnMessage = "IT'S FRIDAAAYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY!!!!!!!!";
  }
  msg.say({
    text:returnMessage,
    attachments: [{
      text: 'DAYBOT SAYS IT\'S FRIDAAAYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY',
      title: 'FRIDAY!!!',
      image_url: 'https://lh3.googleusercontent.com/UYxU7SiFjs1WuoegWgHN5hqWmS82GYf-h8ZsAaCuoCvN3tVJWKStW9-SN7oXLnoUTwUN9V2wvitQexk=w1920-h901',
      title_link: 'http://www.usmanjj.com/',
      color: '#7CD197'
    }]
  });

})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>adding more stuff<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// Catch-all for any other responses not handled above
slapp.message(/^(what day is it\?)/i, ['mention', 'direct_message', 'direct_mention', 'ambient'], (msg) => {
  var now = new Date();
  var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  var day = days[ now.getDay() ];

  var returnMessage = { text: "It's "+days[ now.getDay()] };

  if(day == "Friday"){
    returnMessage = { text: "IT'S FRIDAAAYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY!!!!!!!!",
                       attachments: [{
                          text: 'DAYBOT SAYS IT\'S FRIDAAAYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY',
                          title: 'FRIDAY!!!',
                          image_url: 'https://lh6.googleusercontent.com/xLudRRMFGY24Lu7qjwQa1mRM-8VSNWE2l2L72XYDKnCDJQkbQfFoYajCsnrcVlJqF-OrNp4SabUE7cQ=w1920-h901',
                          title_link: 'http://www.usmanjj.com/',
                          color: '#7CD197'
                        }]
                    };
  }
  msg.say(returnMessage);

})

// Catch-all for any other responses not handled above
slapp.message(/^(testestest\?)/i, ['mention', 'direct_message', 'direct_mention', 'ambient'], (msg) => {
  var now = new Date();
  var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  var day = days[ now.getDay() ];

  var returnMessage = { text: "It's "+days[ now.getDay()] };

    returnMessage = { attachments: [{
                          image_url: 'https://lh6.googleusercontent.com/xLudRRMFGY24Lu7qjwQa1mRM-8VSNWE2l2L72XYDKnCDJQkbQfFoYajCsnrcVlJqF-OrNp4SabUE7cQ=w1920-h901',
                          title_link: 'http://www.usmanjj.com/',
                          color: '#7CD197'
                        }]
                    };

  msg.say(returnMessage);

})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>var restify = require('restify');
var builder = require('botbuilder');

// Get secrets from server environment
var botConnectorOptions = {
    appId: process.env.BOTFRAMEWORK_APPID,
    appSecret: process.env.BOTFRAMEWORK_APPSECRET
};

// Create bot
var bot = new builder.BotConnectorBot(botConnectorOptions);
bot.add('/', function (session) {

    //respond with user's message
    session.send("You said " + session.message.text);
});

// Setup Restify Server
var server = restify.createServer();

// Handle Bot Framework messages
server.post('/api/messages', bot.verifyBotFramework(), bot.listen());

// Serve a static web page
server.get(/.*/, restify.serveStatic({
	'directory': '.',
	'default': 'index.html'
}));

server.listen(process.env.port || 3978, function () {
    console.log('%s listening to %s', server.name, server.url);
});
<commit_msg>updated skype bot<commit_after>const restify = require('restify');
const skype = require('skype-sdk');
const builder = require('botbuilder');

// Initialize the BotService
const botService = new skype.BotService({
    messaging: {
        botId: "dfbc5f3a-53a2-40fe-a123-abefca9f9a7a",
        serverUrl : "https://apis.skype.com",
        requestTimeout : 15000,
        appId: process.env.BOTFRAMEWORK_APPID,
        appSecret: process.env.BOTFRAMEWORK_APPSECRET
    }
});

// Create bot and add dialogs
var bot = new builder.SkypeBot(botService);
bot.add('/', function (session) {
   //respond with user's message
    session.send("You said " + session.message.text);
});

// Setup Restify Server
const server = restify.createServer();
server.post('/api/messages', skype.messagingHandler(botService));

// Serve a static web page
server.get(/.*/, restify.serveStatic({
	'directory': '.',
	'default': 'index.html'
}));

server.listen(process.env.port || 3978, function () {
   console.log('%s listening to %s', server.name, server.url);
});

/*
var restify = require('restify');
var builder = require('botbuilder');

// Get secrets from server environment
var botConnectorOptions = {
    appId: process.env.BOTFRAMEWORK_APPID,
    appSecret: process.env.BOTFRAMEWORK_APPSECRET
};

// Create bot
var bot = new builder.BotConnectorBot(botConnectorOptions);
bot.add('/', function (session) {

    //respond with user's message
    session.send("You said " + session.message.text);
});

// Setup Restify Server
var server = restify.createServer();

// Handle Bot Framework messages
server.post('/api/messages', bot.verifyBotFramework(), bot.listen());

// Serve a static web page
server.get(/.*/  /*, restify.serveStatic({
	'directory': '.',
	'default': 'index.html'
}));
*/
/*
server.listen(process.env.port || 3978, function () {
    console.log('%s listening to %s', server.name, server.url);
});
*/
<|endoftext|>


<commit_before>define([], function(){
    return {
        "name": {
            "default": "New Character",
            "save": true
        },
        "job": {
            "default": "Innkeeper",
            "save": true
        },
        "stats": {
            "array": [
                {
                    "stat": {
                        "save": true,
                        "default": "luk"
                    },
                    "max": {
                        "save": true,
                        "default": 0
                    },
                    "current": {
                        "save": true,
                        "default": 0
                    }

                }
            ],
            "save": true
        },
        "items": {
            "array": [
                {
                    "item": {
                        "save": true,
                        "default": "rock"
                    }
                }
            ]
        }
    }
});<commit_msg>Add ID and selected as UI properties. Add a missing save: true to items<commit_after>define([], function(){
    return {
        "name": {
            "default": "New Character",
            "save": true
        },
        "id": {
            "callback": 0
        },
        "job": {
            "default": "Innkeeper",
            "save": true
        },
        "stats": {
            "array": [
                {
                    "stat": {
                        "save": true,
                        "default": "luk"
                    },
                    "max": {
                        "save": true,
                        "default": 0
                    },
                    "current": {
                        "save": true,
                        "default": 0
                    }

                }
            ],
            "save": true
        },
        "items": {
            "array": [
                {
                    "item": {
                        "save": true,
                        "default": "rock"
                    }
                }
            ],
            "save": true
        },
        "selected": {
            "default": false
        }
    }
});<|endoftext|>


<commit_before>// server.js
// BASE SETUP
// ==============================================

var express = require('express');
var app = express();
var port = process.env.PORT_RUNTIME || process.env.PORT || 3000;
var request = require('request');
var config = require('./config.js');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./sqlite/mopsidb1');
var registryip = getIp();

db.serialize(function () {
  db.run("CREATE TABLE IF NOT EXISTS settings (marathon TEXT, registry TEXT, id INT)");
  db.run("REPLACE INTO settings (marathon, registry, id) VALUES(1,1,1)");
});

function getIp(req, res) {
  db.get('SELECT * FROM settings', function (error, row) {
    if (error !== null) {
      console.error(error);
    } else {
      registryip = row.registry;
      marathonip = row.marathon;

      console.log(row);
      console.log('IPs:' + registryip + ' ' + marathonip);
    }
  });
};

app.get('/settings', function (req, res) {
  db.get("SELECT * FROM settings WHERE id='1'", function (err, row) {
    res.json({
      "marathon": row.marathon,
      "registry": row.registry
    });
  });
});

app.post('/settings', function (req, res) {
  db.run("UPDATE settings SET marathon='" + req.param("marathon") + "', registry='" + req.param("registry") + "' WHERE id='1'", function (error, row) {
    if (error) {
      console.error(error);
      res.status(500);
    } else {
      res.status(202);
    }
    res.end();
  });
});

// REPOS
app.get('/v1/repos', function (req, res) {
  console.log('Get repos');
  req.pipe(request.get(registryip + config.REGLISTREPOS, function (error, response, body) {
    //req.pipe(request.get(config.REGISTRYHOST + config.REGLISTREPOS, function (error, response, body) {
    console.log('[' + new Date() + '] ', req);
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// DELETE REPOS
app.get('/v1/deleterepos/:name', function (req, res, next) {
  req.pipe(request.del(config.REGISTRYHOST + config.REGREPOSTAGS + req.param("name") + '/', function (error, response, body) {
    console.log('[' + new Date() + '] ', req);
    if (error) {
      console.error('Connection error: ' + error.code);
      res.statusCode = error.code;
    }
  })).pipe(res);
});

// TAGS
app.get('/v1/tags', function getTags(req, res) {
  console.log('Get tags');
  req.pipe(request.get(config.REGISTRYHOST + config.REGREPOSTAGS + req.param("name") + '/tags', function (error, response, body) {
    console.log('[' + new Date() + '] ', req.url);
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// LAYER
app.get('/v1/layer', function getLayer(req, res) {
  console.log('Get layer');
  req.pipe(request.get(config.REGISTRYHOST + config.REG_IMAGE_LAYER + req.param("id") + '/json', function (error, response, body) {
    console.log('[' + new Date() + '] ', req.url);
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// list all running apps
app.get(config.LISTAPPS, function getApps(req, res) {
  console.log('Get running apps');
  req.pipe(request.get(marathonip + config.MARATHONLISTAPPS, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// get infos of a running app
app.get(config.GETINFOSAPP, function getAppInfo(req, res) {
  console.log('Get info of app: ' + req.params.id);
  req.pipe(request.get(config.MARATHONHOST + config.MARATHONGETINFOSAPP + req.params.id, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// stop a app
app.delete(config.DELETEAPP, function deleteApps(req, res) {
  console.log('Delete an app');
  req.pipe(request.del(config.MARATHONHOST + config.MARATHONDELETEAPP + req.params.id, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// deploy a app
app.post(config.DEPLOYAPP, function deployApps(req, res) {
  console.log('Deploy an app');
  req.pipe(request.post(config.MARATHONHOST + config.MARATHONDEPLOYAPP, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// change params of a app
app.put(config.CHANGEAPP, function changeApps(req, res) {
  console.log('Change an app: ' + req.params.id);
  req.pipe(request.put(config.MARATHONHOST + config.MARATHONCHANGEAPP + req.params.id, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// catch uncaught exception
process.on('uncaughtException', function (err) {
  console.error('uncaughtException: ' + err.message);
  console.error(err.stack);
  process.exit(1);
});

// get docker logs of a running app
app.get(config.DOCKERLOG, function getDockerLog(req, res) {
  console.log('Get logs of container: ' + req.params.id);
  req.pipe(request.get({
    url: config.DOCKERHOST + config.DOCKERLOGPART1 + req.params.id + '/logs',
    qs: req.query
  }, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// get running docker containers
app.get(config.DOCKERLIST, function getDockerLog(req, res) {
  console.log('Get all containers');
  req.pipe(request.get(config.DOCKERHOST1 + config.DOCKERLIST, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);

  //Simple test
  console.log('Get all containers');
  req.pipe(request.get(config.DOCKERHOST2 + config.DOCKERLIST, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

app.use(express.static(__dirname + '/public'));

// START THE SERVER
// ==============================================
app.listen(port);
console.log('Mopsi  aka mopsi brain snoops on port ' + port);
<commit_msg>marathonip<commit_after>// server.js
// BASE SETUP
// ==============================================

var express = require('express');
var app = express();
var port = process.env.PORT_RUNTIME || process.env.PORT || 3000;
var request = require('request');
var config = require('./config.js');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./sqlite/mopsidb1');
var registryip = getIp();
var marathonip = getIp();

db.serialize(function () {
  db.run("CREATE TABLE IF NOT EXISTS settings (marathon TEXT, registry TEXT, id INT)");
  db.run("REPLACE INTO settings (marathon, registry, id) VALUES('http://192.168.1.180:8080/','http://192.168.1.188:5000/','1')");
});

function getIp(req, res) {
  db.get('SELECT * FROM settings', function (error, row) {
    if (error !== null) {
      console.error(error);
    } else {
      registryip = row.registry;
      marathonip = row.marathon;

      console.log(row);
      console.log('IPs:' + registryip + ' ' + marathonip);
    }
  });
};

app.get('/settings', function (req, res) {
  db.get("SELECT * FROM settings WHERE id='1'", function (err, row) {
    res.json({
      "marathon": row.marathon,
      "registry": row.registry
    });
  });
});

app.post('/settings', function (req, res) {
  db.run("UPDATE settings SET marathon='" + req.param("marathon") + "', registry='" + req.param("registry") + "' WHERE id='1'", function (error, row) {
    if (error) {
      console.error(error);
      res.status(500);
    } else {
      res.status(202);
    }
    res.end();
  });
});

// REPOS
app.get('/v1/repos', function (req, res) {
  console.log('Get repos');
  req.pipe(request.get(registryip + config.REGLISTREPOS, function (error, response, body) {
    //req.pipe(request.get(config.REGISTRYHOST + config.REGLISTREPOS, function (error, response, body) {
    console.log('[' + new Date() + '] ', req);
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// DELETE REPOS
app.get('/v1/deleterepos/:name', function (req, res, next) {
  req.pipe(request.del(config.REGISTRYHOST + config.REGREPOSTAGS + req.param("name") + '/', function (error, response, body) {
    console.log('[' + new Date() + '] ', req);
    if (error) {
      console.error('Connection error: ' + error.code);
      res.statusCode = error.code;
    }
  })).pipe(res);
});

// TAGS
app.get('/v1/tags', function getTags(req, res) {
  console.log('Get tags');
  req.pipe(request.get(config.REGISTRYHOST + config.REGREPOSTAGS + req.param("name") + '/tags', function (error, response, body) {
    console.log('[' + new Date() + '] ', req.url);
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// LAYER
app.get('/v1/layer', function getLayer(req, res) {
  console.log('Get layer');
  req.pipe(request.get(config.REGISTRYHOST + config.REG_IMAGE_LAYER + req.param("id") + '/json', function (error, response, body) {
    console.log('[' + new Date() + '] ', req.url);
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// list all running apps
app.get(config.LISTAPPS, function getApps(req, res) {
  console.log('Get running apps');
  req.pipe(request.get(marathonip + config.MARATHONLISTAPPS, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// get infos of a running app
app.get(config.GETINFOSAPP, function getAppInfo(req, res) {
  console.log('Get info of app: ' + req.params.id);
  req.pipe(request.get(config.MARATHONHOST + config.MARATHONGETINFOSAPP + req.params.id, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// stop a app
app.delete(config.DELETEAPP, function deleteApps(req, res) {
  console.log('Delete an app');
  req.pipe(request.del(config.MARATHONHOST + config.MARATHONDELETEAPP + req.params.id, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// deploy a app
app.post(config.DEPLOYAPP, function deployApps(req, res) {
  console.log('Deploy an app');
  req.pipe(request.post(config.MARATHONHOST + config.MARATHONDEPLOYAPP, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// change params of a app
app.put(config.CHANGEAPP, function changeApps(req, res) {
  console.log('Change an app: ' + req.params.id);
  req.pipe(request.put(config.MARATHONHOST + config.MARATHONCHANGEAPP + req.params.id, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// catch uncaught exception
process.on('uncaughtException', function (err) {
  console.error('uncaughtException: ' + err.message);
  console.error(err.stack);
  process.exit(1);
});

// get docker logs of a running app
app.get(config.DOCKERLOG, function getDockerLog(req, res) {
  console.log('Get logs of container: ' + req.params.id);
  req.pipe(request.get({
    url: config.DOCKERHOST + config.DOCKERLOGPART1 + req.params.id + '/logs',
    qs: req.query
  }, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

// get running docker containers
app.get(config.DOCKERLIST, function getDockerLog(req, res) {
  console.log('Get all containers');
  req.pipe(request.get(config.DOCKERHOST1 + config.DOCKERLIST, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);

  //Simple test
  console.log('Get all containers');
  req.pipe(request.get(config.DOCKERHOST2 + config.DOCKERLIST, function (error, response, body) {
    if (error) {
      console.error('Connection error: ' + error.code);
    }
  })).pipe(res);
});

app.use(express.static(__dirname + '/public'));

// START THE SERVER
// ==============================================
app.listen(port);
console.log('Mopsi  aka mopsi brain snoops on port ' + port);
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var http = require('http');
var mongoose = require('mongoose');
var celebsRoutes = require('./routes/celebs-routes');

mongoose.connect(process.env.MONGO_URI || 'mongodb://localhost/db-cel');

var app = express();
app.use(express.static(__dirname + '/build'));

var router = express.Router();

celebsRoutes(router);

app.use('/', router);

http.createServer(app).listen(process.env.PORT || 3000, function() {
  console.log('The server is listening on port ' + (process.env.PORT || 3000));
});
<commit_msg>deploy<commit_after>'use strict';

var express = require('express');
var http = require('http');
var mongoose = require('mongoose');
var celebsRoutes = require('./routes/celebs-routes');

mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://localhost/db-cel');

var app = express();
app.use(express.static(__dirname + '/build'));

var router = express.Router();

celebsRoutes(router);

app.use('/', router);

http.createServer(app).listen(process.env.PORT || 3000, function() {
  console.log('The server is listening on port ' + (process.env.PORT || 3000));
});
<|endoftext|>


<commit_before>var express = require('express'),
app = express(),
path = require('path'),
port = (process.argv[2] || 8000);

app.get('/api/:file.json', function(req, res) {
  console.log(req.params.file);

  var response = [
    {
      "id": 1,
      "title": "SUPER",
      "description": "Salesforce Upcoming Projects Evaluation Rankings",
      "favorite": false
    },
    {
      "id": 2,
      "title": "Über",
      "description": "Ünderständing better external resources",
      "favorite": false
    }
  ];

  res.json(response);
});

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

app.listen(port);

console.log("Running on http://localhost:" + port + " \nCTRL + C to shutdown");<commit_msg>Add whitespace for git's enjoyment<commit_after>var express = require('express'),
app = express(),
path = require('path'),
port = (process.argv[2] || 8000);

app.get('/api/:file.json', function(req, res) {
  console.log(req.params.file);

  var response = [
    {
      "id": 1,
      "title": "SUPER",
      "description": "Salesforce Upcoming Projects Evaluation Rankings",
      "favorite": false
    },
    {
      "id": 2,
      "title": "Über",
      "description": "Ünderständing better external resources",
      "favorite": false
    }
  ];

  res.json(response);
});

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

app.listen(port);

console.log("Running on http://localhost:" + port + " \nCTRL + C to shutdown");
<|endoftext|>


<commit_before>"use strict";

var express = require('express');
var bodyParser = require('body-parser');
var compress = require('compression')();
var pages = require('./routes/pages.js');
var signup = require('./routes/signup.js');

var app = express();

// Configuration
var secret = process.env.COOKIE_SECRET || 'secret';

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.use(bodyParser());
app.use(compress);

if (app.get('env') === 'development') {
  app.use(require('errorhandler')({
    dumpExceptions: true,
    showStack: true
  }));
} else {
  app.use(require('errorhandler')());
}

// Routes
app.get('/', pages.index);
app.get('/contact', pages.contact);
app.post('/signup', signup.sendToMailchimp);
app.get('/signup', function(req, res){
  res.redirect('/');
});

app.use(express.static(__dirname + '/dist'));

// Go
app.listen(process.env.port || 3000);
console.log("Express server started");<commit_msg>Consistency<commit_after>"use strict";

var express = require('express');
var bodyParser = require('body-parser')();
var compress = require('compression')();
var pages = require('./routes/pages.js');
var signup = require('./routes/signup.js');

var app = express();

// Configuration
var secret = process.env.COOKIE_SECRET || 'secret';

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.use(bodyParser);
app.use(compress);

if (app.get('env') === 'development') {
  app.use(require('errorhandler')({
    dumpExceptions: true,
    showStack: true
  }));
} else {
  app.use(require('errorhandler')());
}

// Routes
app.get('/', pages.index);
app.get('/contact', pages.contact);
app.post('/signup', signup.sendToMailchimp);
app.get('/signup', function(req, res){
  res.redirect('/');
});

app.use(express.static(__dirname + '/dist'));

// Go
app.listen(process.env.port || 3000);
console.log("Express server started");<|endoftext|>


<commit_before>var express = require('express'),
    fs = require('fs'),
    jsapi = require('./routes/jsapi'),
    person = require('./routes/person'),
    shuttle = require('./routes/shuttle'),
    map = require('./routes/map'),
    fitness = require('./routes/fitness'),
    library = require('./routes/library'),
    nodeUserGid = 'node',
    nodeUserUid = 'node';

var app = express();
var logFile;

logFile = fs.createWriteStream(__dirname + '/logs/http.' + Date.now());

app.use(express.logger({stream: logFile}));
app.use(express.compress());

app.use('/static', express.static(__dirname + '/static'));

// Instruct Android 2.x browser to not cache CORS results because it will return 0/empty from cache.
// We want to limit this damage to Android 2.x because caching requests for a short period of time
//    is a good idea. But, uh, only if the caching implementation works. Definitely broken in Android 2.3
var android2RegExp = / Android 2\./;
app.use(function (req, res, next) {
    'use strict';
    if (android2RegExp.test(req.headers['user-agent'])) {
        res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
        res.header('Expires', '0');
    }
    next();
});

app.use(function (req, res, next) {
    'use strict';

    res.header('Access-Control-Allow-Origin', '*');

    if (req.headers['access-control-request-method']) {
        res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    }
    if (req.headers['access-control-request-headers']) {
        res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    }

    res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);

    if (req.method === 'OPTIONS') {
        res.send(200);
    } else  {
        next();
    }
});

app.use(function (err, req, res, undefined) {
    'use strict';
    console.dir(err);
    res.send(500, 'Server error');
});

app.get('/jsapi', jsapi.load);

app.get('/person/search', person.search);

app.get('/shuttle/plan', shuttle.plan);
app.get('/shuttle/routes', shuttle.routes);
app.get('/shuttle/stops', shuttle.stops);
app.get('/shuttle/times', shuttle.times);
app.get('/shuttle/predictions', shuttle.predictions);

app.get('/map/tile/:zoom/:x/:y', map.tile);

app.get('/fitness/schedule', fitness.schedule);

app.get('/library/hours', library.hours);
app.get('/library/guides', library.guides);

app.get('/', function (req, res) {
    'use strict';
    res.sendfile(__dirname + '/static/index.html');
});

app.listen(80, function () {
    'use strict';
    process.setgid(nodeUserGid);
    process.setuid(nodeUserUid);
});

console.log('Listening on port 80...');<commit_msg>enable ssl<commit_after>var express = require('express'),
    fs = require('fs'),
    http = require('http'),
    https = require('https'),
    jsapi = require('./routes/jsapi'),
    person = require('./routes/person'),
    shuttle = require('./routes/shuttle'),
    map = require('./routes/map'),
    fitness = require('./routes/fitness'),
    library = require('./routes/library'),
    nodeUserGid = 'node',
    nodeUserUid = 'node',
    sslKey = '/etc/pki/tls/private/apis_ucsf_edu.key',
    sslCert = '/etc/pki/tls/certs/apis_ucsf_edu_cert.cer';

var setIds = function () {
    'use strict';
    process.setgid(nodeUserGid);
    process.setuid(nodeUserUid);
};

var httpsOptions = {
    key: fs.readFileSync(sslKey),
    cert: fs.readFileSync(sslCert)
};

var app = express();
var logFile;

logFile = fs.createWriteStream(__dirname + '/logs/http.' + Date.now());

app.use(express.logger({stream: logFile}));
app.use(express.compress());

app.use('/static', express.static(__dirname + '/static'));

// Instruct Android 2.x browser to not cache CORS results because it will return 0/empty from cache.
// We want to limit this damage to Android 2.x because caching requests for a short period of time
//    is a good idea. But, uh, only if the caching implementation works. Definitely broken in Android 2.3
var android2RegExp = / Android 2\./;
app.use(function (req, res, next) {
    'use strict';
    if (android2RegExp.test(req.headers['user-agent'])) {
        res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
        res.header('Expires', '0');
    }
    next();
});

app.use(function (req, res, next) {
    'use strict';

    res.header('Access-Control-Allow-Origin', '*');

    if (req.headers['access-control-request-method']) {
        res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    }
    if (req.headers['access-control-request-headers']) {
        res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    }

    res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);

    if (req.method === 'OPTIONS') {
        res.send(200);
    } else  {
        next();
    }
});

app.use(function (err, req, res, undefined) {
    'use strict';
    console.dir(err);
    res.send(500, 'Server error');
});

app.get('/jsapi', jsapi.load);

app.get('/person/search', person.search);

app.get('/shuttle/plan', shuttle.plan);
app.get('/shuttle/routes', shuttle.routes);
app.get('/shuttle/stops', shuttle.stops);
app.get('/shuttle/times', shuttle.times);
app.get('/shuttle/predictions', shuttle.predictions);

app.get('/map/tile/:zoom/:x/:y', map.tile);

app.get('/fitness/schedule', fitness.schedule);

app.get('/library/hours', library.hours);
app.get('/library/guides', library.guides);

app.get('/', function (req, res) {
    'use strict';
    res.sendfile(__dirname + '/static/index.html');
});

http.createServer(app).listen(80, setIds);
console.log('Serving HTTP on port 80...');
try {
    https.createServer(httpsOptions, app).listen(443, setIds);
    console.log('Serving HTTPS on port 443...');
} catch (e) {
    console.error('Cannot start with SSL: ' + e.message);
}
<|endoftext|>


<commit_before>// @see: https://gist.github.com/branneman/8048520
require('app-module-path').addPath(__dirname + '/lib');

var server = require('nodebootstrap-server')
  , app    = require('express')();

app = require('nodebootstrap-htmlapp').setup(app);

server.setup(app, function(runningApp) {

  // Nothing ever comes from "x-powered-by", but a security hole
  runningApp.disable("x-powered-by");

  // Choose your favorite view engine(s)
  runningApp.set('view engine', 'handlebars');
  runningApp.engine('handlebars', require('hbs').__express);

  //// you could use two view engines in parallel (if you are brave):
  // runningApp.set('view engine', 'j2');
  // runningApp.engine('j2', require('swig').renderFile);

  //---- Mounting well-encapsulated application modules (so-called: "mini-apps")
  //---- See: http://expressjs.com/guide/routing.html and http://vimeo.com/56166857
  runningApp.use('/hello', require('hello')); // attach to sub-route

  // API endpoint attached to root route:
  runningApp.use('/', require('homedoc')); // attach to root route

  // If you need websockets:
  // var socketio = require('socket.io')(runningApp.http);
  // require('fauxchatapp')(socketio);

});
<commit_msg>Separating out the location of user defined custom configuration and the actual running of the server in server.js to enable endpoint testing.<commit_after>// @see: https://gist.github.com/branneman/8048520
require('app-module-path').addPath(__dirname + '/lib');

var server = require('nodebootstrap-server')
  , appConfig = require('./appConfig')
  , app    = require('express')();

app = require('nodebootstrap-htmlapp').setup(app);

server.setup(app, appConfig.setup);
<|endoftext|>