<commit_before>define([
    'jquery',
    'underscore',
    'backbone',
    'views/navigationtree/NavigationTreeView',
    'views/projects/ViewNodeItemView',
    'views/testsuites/NewTestSuiteView',
    'views/testsuites/TestSuiteView',
    'views/testsuites/ConfirmDeleteTestSuiteView',
    'views/testcases/NewTestCaseView',
    'views/testcases/TestCaseView',
    'views/testcases/ConfirmDeleteTestCaseView',
    'models/project/ProjectModel',
    'models/testsuite/TestSuiteModel',
    'models/testcase/TestCaseModel',
    'collections/core/ExecutionTypesCollection',
    'text!templates/projects/viewProjectTemplate.html',
    'text!templates/projects/projectNodeItemTemplate.html',
    'text!templates/testsuites/testSuiteNodeItemTemplate.html',
    'text!templates/testcases/testCaseNodeItemTemplate.html'
], function(
    $,
    _,
    Backbone,
    NavigationTreeView,
    ViewNodeItemView,
    NewTestSuiteView,
    TestSuiteView,
    ConfirmDeleteTestSuiteView,
    NewTestCaseView,
    TestCaseView,
    ConfirmDeleteTestCaseView,
    ProjectModel,
    TestSuiteModel,
    TestCaseModel,
    ExecutionTypesCollection,
    viewProjectTemplate,
    projectNodeItemTemplate,
    testSuiteNodeItemTemplate,
    testCaseNodeItemTemplate) {

    /**
     * Displays the navigation tree.
     */
    var ViewProjectView = Backbone.View.extend({
        el: $("#page"),

        events: {},

        initialize: function(options) {
            _.bindAll(this,
                'render',
                'setProjectId',
                'setTestSuiteId',
                'setTestCaseId',
                'updateNavigationTree',
                'displayProject',
                'displayNewTestSuite',
                'displayTestSuite',
                'displayShowTestSuite',
                'displayConfirmDeleteTestSuite',
                'displayNewTestCase',
                'displayTestCase',
                'displayShowTestCase',
                'displayConfirmDeleteTestCase');

            this.projectId = 0;
            if (typeof options !== typeof undefined && typeof options.projectId !== typeof undefined) {
                this.projectId = parseInt(options.projectId);
            }
            this.testSuiteId = 0;
            this.testCaseId = 0;

            // Views
            this.navigationTreeView = new NavigationTreeView({
                draggable: true
            });
            this.viewNodeItemView = new ViewNodeItemView();
            this.newTestSuiteView = new NewTestSuiteView();
            this.newTestCaseView = new NewTestCaseView();
            this.testSuiteView = new TestSuiteView();
            this.confirmDeleteTestSuiteView = new ConfirmDeleteTestSuiteView();
            this.testCaseView = new TestCaseView();
            this.confirmDeleteTestCaseView = new ConfirmDeleteTestCaseView();

            // Collections
            this.executionTypesCollection = new ExecutionTypesCollection();

            // Events
            Backbone.on('nestor:navigationtree:project_changed', this.updateNavigationTree);
            Backbone.on('nestor:navigationtree_changed', this.updateNavigationTree);

            // For GC
            this.subviews = new Object();
            this.subviews.navigationTreeView = this.navigationTreeView;
            this.subviews.viewNodeItemView = this.viewNodeItemView;
            this.subviews.newTestSuiteView = this.newTestSuiteView;
            this.subviews.testSuiteView = this.testSuiteView;
            this.subviews.confirmDeleteTestSuiteView = this.confirmDeleteTestSuiteView;
            this.subviews.newTestCaseView = this.newTestCaseView;
            this.subviews.testCaseView = this.testCaseView;
            this.subviews.confirmDeleteTestCaseView = this.confirmDeleteTestCaseView;
        },

        render: function() {
            console.log("RENDER " + this.projectId);
            $('.item').removeClass('active');
            $('.item a[href="#/specification"]').parent().addClass('active');
            var compiledTemplate = _.template(viewProjectTemplate, {});
            this.$el.html(compiledTemplate);

            this.$('#content-main').empty();
            this.updateNavigationTree();
        },

        setProjectId: function(id) {
            var projectId = parseInt(id);
            // update project ID in models
            this.projectModel = new ProjectModel();
            this.projectModel.id = projectId;

            this.testSuiteModel = new TestSuiteModel();
            this.testSuiteModel.project_id = projectId;

            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = projectId;

            this.navigationTreeView.projectId = projectId;

            if (this.projectId !== projectId/* || !$.trim($(this.navigationTreeView.el).html())*/) {
                this.projectId = projectId;
                Backbone.trigger('nestor:navigationtree:project_changed');
            }
        },

        setTestSuiteId: function(testSuiteId) {
            // update test suite ID in models
            this.testSuiteModel = new TestSuiteModel();
            this.testSuiteModel.project_id = this.projectId;
            this.testSuiteModel.id = testSuiteId;
            this.testSuiteId = testSuiteId;

            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = this.projectId;
            this.testCaseModel.testsuite_id = testSuiteId;
        },

        setTestCaseId: function(testCaseId) {
            // update test suite ID in models
            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = this.projectId;
            this.testCaseModel.testsuite_id = this.testSuiteId;
            this.testCaseModel.id = testCaseId;

            this.testCaseId = testCaseId;
        },

        updateNavigationTree: function(event) {
            console.log("UPDATE NAVIGATION TREE");
            console.log('Rendering navigation tree!');
            this.$('#navigation-tree').fancytree({});
            this.navigationTreeView.render({
                el: this.$('#navigation-tree')
            });
        },

        displayLoading: function() {
            this.$('#content-main').empty();
            this.$('#content-main').html('

');
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayProject: function() {
            this.displayLoading();
            var self = this;
            this.projectModel.fetch({
                success: function(responseData) {
                    var data = {
                        project: self.projectModel,
                        _: _
                    };

                    var compiledTemplate = _.template(projectNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    this.$('#content-main').empty();
                    this.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch project");
                }
            });
        },

        /**
         * Display new test suite form.
         */
        displayNewTestSuite: function() {
            this.displayLoading();
            this.newTestSuiteView.render({
                parent_id: this.parentId,
                project_id: this.projectId
            });
            this.newTestSuiteView.delegateEvents();
            this.$('#content-main').empty();
            this.$('#content-main').append(this.newTestSuiteView.el);
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayTestSuite: function() {
            this.displayLoading();
            var self = this;
            this.testSuiteModel.set('id', this.testSuiteId);
            this.testSuiteModel.fetch({
                success: function(responseData) {
                    var data = {
                        testsuite: self.testSuiteModel,
                        _: _
                    };

                    var compiledTemplate = _.template(testSuiteNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        /**
         * Display test suite item on the right panel of the screen for edit.
         */
        displayShowTestSuite: function() {
            this.displayLoading();
            var self = this;
            this.testSuiteModel.set('id', this.testSuiteId);
            this.testSuiteModel.fetch({
                success: function(responseData) {
                    self.testSuiteView.render({
                        model: self.testSuiteModel,
                        project_id: self.projectId
                    });
                    self.testSuiteView.delegateEvents();
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.testSuiteView.el);
                    setTimeout(function() {
                        self.testSuiteView.simplemde.value(self.testSuiteView.model.get('description'));
                        self.testSuiteView.simplemde.codemirror.refresh();
                    }, 1);
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        displayConfirmDeleteTestSuite: function() {
            this.displayLoading();
            var self = this;
            this.testSuiteModel.set('id', this.testSuiteId);
            this.testSuiteModel.fetch({
                success: function(responseData) {
                    self.confirmDeleteTestSuiteView.render({
                        model: self.testSuiteModel,
                        project_id: self.projectId
                    });
                    self.confirmDeleteTestSuiteView.delegateEvents();
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.confirmDeleteTestSuiteView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        /**
         * Display new test case form.
         */
        displayNewTestCase: function() {
            this.displayLoading();
            var self = this;
            this.executionTypesCollection.fetch({
                success: function() {
                    self.newTestCaseView.render({
                        project_id: self.projectId,
                        testsuite_id: self.testSuiteId,
                        execution_types: self.executionTypesCollection.models
                    });
                    self.newTestCaseView.delegateEvents();
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.newTestCaseView.el);
                },
                error: function() {
                    throw new Error('Failure to retrieve executiont types!');
                }
            });
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayTestCase: function() {
            this.displayLoading();
            var self = this;
            this.testCaseModel.set('project_id', this.projectId);
            this.testCaseModel.set('test_suite_id', this.testSuiteId);
            this.testCaseModel.set('id', this.testCaseId);
            this.testCaseModel.fetch({
                success: function(responseData) {
                    var data = {
                        testcase: self.testCaseModel,
                        _: _
                    };

                    var compiledTemplate = _.template(testCaseNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test case");
                }
            });
        },

        /**
         * Display test case item on the right panel of the screen for edit.
         */
        displayShowTestCase: function() {
            this.displayLoading();
            var self = this;
            this.testCaseModel.set('project_id', this.projectId);
            this.testCaseModel.set('test_suite_id', this.testSuiteId);
            this.testCaseModel.set('id', this.testCaseId);
            this.testCaseModel.fetch({
                success: function(responseData) {
                    self.executionTypesCollection.fetch({
                        success: function() {
                            self.testCaseView.render({
                                model: self.testCaseModel,
                                test_case_id: self.testCaseId,
                                project_id: self.projectId,
                                test_suite_id: self.testSuiteId,
                                execution_types: self.executionTypesCollection.models
                            });
                            self.testCaseView.delegateEvents();
                            self.$('#content-main').empty();
                            self.$('#content-main').append(self.testCaseView.el);
                            setTimeout(function() {
                                self.testCaseView.description_simplemde.value(self.testCaseView.model.get('version')['description']);
                                self.testCaseView.description_simplemde.codemirror.refresh();
                            }, 1);
                            setTimeout(function() {
                                self.testCaseView.prerequisite_simplemde.value(self.testCaseView.model.get('version')['prerequisite']);
                                self.testCaseView.prerequisite_simplemde.codemirror.refresh();
                            }, 1);
                        },
                        error: function() {
                            throw new Error('Failure to retrieve executiont types!');
                        }
                    });
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        displayConfirmDeleteTestCase: function() {
            this.displayLoading();
            var self = this;
            this.testCaseModel.set('project_id', this.projectId);
            this.testCaseModel.set('test_suite_id', this.testSuiteId);
            this.testCaseModel.set('id', this.testCaseId);
            this.testCaseModel.fetch({
                success: function(responseData) {
                    self.executionTypesCollection.fetch({
                        success: function() {
                            self.confirmDeleteTestCaseView.render({
                                model: self.testCaseModel,
                                project_id: self.projectId,
                                test_suite_id: self.testSuiteId,
                                execution_types: self.executionTypesCollection.models
                            });
                            self.confirmDeleteTestCaseView.delegateEvents();
                            self.$('#content-main').empty();
                            self.$('#content-main').append(self.confirmDeleteTestCaseView.el);
                        },
                        error: function() {
                            throw new Error('Failure to retrieve executiont types!');
                        }
                    });
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

    });

    return ViewProjectView;

});<commit_msg>Remove debug messages<commit_after>define([
    'jquery',
    'underscore',
    'backbone',
    'views/navigationtree/NavigationTreeView',
    'views/projects/ViewNodeItemView',
    'views/testsuites/NewTestSuiteView',
    'views/testsuites/TestSuiteView',
    'views/testsuites/ConfirmDeleteTestSuiteView',
    'views/testcases/NewTestCaseView',
    'views/testcases/TestCaseView',
    'views/testcases/ConfirmDeleteTestCaseView',
    'models/project/ProjectModel',
    'models/testsuite/TestSuiteModel',
    'models/testcase/TestCaseModel',
    'collections/core/ExecutionTypesCollection',
    'text!templates/projects/viewProjectTemplate.html',
    'text!templates/projects/projectNodeItemTemplate.html',
    'text!templates/testsuites/testSuiteNodeItemTemplate.html',
    'text!templates/testcases/testCaseNodeItemTemplate.html'
], function(
    $,
    _,
    Backbone,
    NavigationTreeView,
    ViewNodeItemView,
    NewTestSuiteView,
    TestSuiteView,
    ConfirmDeleteTestSuiteView,
    NewTestCaseView,
    TestCaseView,
    ConfirmDeleteTestCaseView,
    ProjectModel,
    TestSuiteModel,
    TestCaseModel,
    ExecutionTypesCollection,
    viewProjectTemplate,
    projectNodeItemTemplate,
    testSuiteNodeItemTemplate,
    testCaseNodeItemTemplate) {

    /**
     * Displays the navigation tree.
     */
    var ViewProjectView = Backbone.View.extend({
        el: $("#page"),

        events: {},

        initialize: function(options) {
            _.bindAll(this,
                'render',
                'setProjectId',
                'setTestSuiteId',
                'setTestCaseId',
                'updateNavigationTree',
                'displayProject',
                'displayNewTestSuite',
                'displayTestSuite',
                'displayShowTestSuite',
                'displayConfirmDeleteTestSuite',
                'displayNewTestCase',
                'displayTestCase',
                'displayShowTestCase',
                'displayConfirmDeleteTestCase');

            this.projectId = 0;
            if (typeof options !== typeof undefined && typeof options.projectId !== typeof undefined) {
                this.projectId = parseInt(options.projectId);
            }
            this.testSuiteId = 0;
            this.testCaseId = 0;

            // Views
            this.navigationTreeView = new NavigationTreeView({
                draggable: true
            });
            this.viewNodeItemView = new ViewNodeItemView();
            this.newTestSuiteView = new NewTestSuiteView();
            this.newTestCaseView = new NewTestCaseView();
            this.testSuiteView = new TestSuiteView();
            this.confirmDeleteTestSuiteView = new ConfirmDeleteTestSuiteView();
            this.testCaseView = new TestCaseView();
            this.confirmDeleteTestCaseView = new ConfirmDeleteTestCaseView();

            // Collections
            this.executionTypesCollection = new ExecutionTypesCollection();

            // Events
            Backbone.on('nestor:navigationtree:project_changed', this.updateNavigationTree);
            Backbone.on('nestor:navigationtree_changed', this.updateNavigationTree);

            // For GC
            this.subviews = new Object();
            this.subviews.navigationTreeView = this.navigationTreeView;
            this.subviews.viewNodeItemView = this.viewNodeItemView;
            this.subviews.newTestSuiteView = this.newTestSuiteView;
            this.subviews.testSuiteView = this.testSuiteView;
            this.subviews.confirmDeleteTestSuiteView = this.confirmDeleteTestSuiteView;
            this.subviews.newTestCaseView = this.newTestCaseView;
            this.subviews.testCaseView = this.testCaseView;
            this.subviews.confirmDeleteTestCaseView = this.confirmDeleteTestCaseView;
        },

        render: function() {
            $('.item').removeClass('active');
            $('.item a[href="#/specification"]').parent().addClass('active');
            var compiledTemplate = _.template(viewProjectTemplate, {});
            this.$el.html(compiledTemplate);

            this.$('#content-main').empty();
            this.updateNavigationTree();
        },

        setProjectId: function(id) {
            var projectId = parseInt(id);
            // update project ID in models
            this.projectModel = new ProjectModel();
            this.projectModel.id = projectId;

            this.testSuiteModel = new TestSuiteModel();
            this.testSuiteModel.project_id = projectId;

            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = projectId;

            this.navigationTreeView.projectId = projectId;

            if (this.projectId !== projectId/* || !$.trim($(this.navigationTreeView.el).html())*/) {
                this.projectId = projectId;
                Backbone.trigger('nestor:navigationtree:project_changed');
            }
        },

        setTestSuiteId: function(testSuiteId) {
            // update test suite ID in models
            this.testSuiteModel = new TestSuiteModel();
            this.testSuiteModel.project_id = this.projectId;
            this.testSuiteModel.id = testSuiteId;
            this.testSuiteId = testSuiteId;

            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = this.projectId;
            this.testCaseModel.testsuite_id = testSuiteId;
        },

        setTestCaseId: function(testCaseId) {
            // update test suite ID in models
            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = this.projectId;
            this.testCaseModel.testsuite_id = this.testSuiteId;
            this.testCaseModel.id = testCaseId;

            this.testCaseId = testCaseId;
        },

        updateNavigationTree: function(event) {
            console.log('Rendering navigation tree!');
            this.$('#navigation-tree').fancytree({});
            this.navigationTreeView.render({
                el: this.$('#navigation-tree')
            });
        },

        displayLoading: function() {
            this.$('#content-main').empty();
            this.$('#content-main').html('

');
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayProject: function() {
            this.displayLoading();
            var self = this;
            this.projectModel.fetch({
                success: function(responseData) {
                    var data = {
                        project: self.projectModel,
                        _: _
                    };

                    var compiledTemplate = _.template(projectNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    this.$('#content-main').empty();
                    this.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch project");
                }
            });
        },

        /**
         * Display new test suite form.
         */
        displayNewTestSuite: function() {
            this.displayLoading();
            this.newTestSuiteView.render({
                parent_id: this.parentId,
                project_id: this.projectId
            });
            this.newTestSuiteView.delegateEvents();
            this.$('#content-main').empty();
            this.$('#content-main').append(this.newTestSuiteView.el);
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayTestSuite: function() {
            this.displayLoading();
            var self = this;
            this.testSuiteModel.set('id', this.testSuiteId);
            this.testSuiteModel.fetch({
                success: function(responseData) {
                    var data = {
                        testsuite: self.testSuiteModel,
                        _: _
                    };

                    var compiledTemplate = _.template(testSuiteNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        /**
         * Display test suite item on the right panel of the screen for edit.
         */
        displayShowTestSuite: function() {
            this.displayLoading();
            var self = this;
            this.testSuiteModel.set('id', this.testSuiteId);
            this.testSuiteModel.fetch({
                success: function(responseData) {
                    self.testSuiteView.render({
                        model: self.testSuiteModel,
                        project_id: self.projectId
                    });
                    self.testSuiteView.delegateEvents();
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.testSuiteView.el);
                    setTimeout(function() {
                        self.testSuiteView.simplemde.value(self.testSuiteView.model.get('description'));
                        self.testSuiteView.simplemde.codemirror.refresh();
                    }, 1);
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        displayConfirmDeleteTestSuite: function() {
            this.displayLoading();
            var self = this;
            this.testSuiteModel.set('id', this.testSuiteId);
            this.testSuiteModel.fetch({
                success: function(responseData) {
                    self.confirmDeleteTestSuiteView.render({
                        model: self.testSuiteModel,
                        project_id: self.projectId
                    });
                    self.confirmDeleteTestSuiteView.delegateEvents();
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.confirmDeleteTestSuiteView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        /**
         * Display new test case form.
         */
        displayNewTestCase: function() {
            this.displayLoading();
            var self = this;
            this.executionTypesCollection.fetch({
                success: function() {
                    self.newTestCaseView.render({
                        project_id: self.projectId,
                        testsuite_id: self.testSuiteId,
                        execution_types: self.executionTypesCollection.models
                    });
                    self.newTestCaseView.delegateEvents();
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.newTestCaseView.el);
                },
                error: function() {
                    throw new Error('Failure to retrieve executiont types!');
                }
            });
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayTestCase: function() {
            this.displayLoading();
            var self = this;
            this.testCaseModel.set('project_id', this.projectId);
            this.testCaseModel.set('test_suite_id', this.testSuiteId);
            this.testCaseModel.set('id', this.testCaseId);
            this.testCaseModel.fetch({
                success: function(responseData) {
                    var data = {
                        testcase: self.testCaseModel,
                        _: _
                    };

                    var compiledTemplate = _.template(testCaseNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test case");
                }
            });
        },

        /**
         * Display test case item on the right panel of the screen for edit.
         */
        displayShowTestCase: function() {
            this.displayLoading();
            var self = this;
            this.testCaseModel.set('project_id', this.projectId);
            this.testCaseModel.set('test_suite_id', this.testSuiteId);
            this.testCaseModel.set('id', this.testCaseId);
            this.testCaseModel.fetch({
                success: function(responseData) {
                    self.executionTypesCollection.fetch({
                        success: function() {
                            self.testCaseView.render({
                                model: self.testCaseModel,
                                test_case_id: self.testCaseId,
                                project_id: self.projectId,
                                test_suite_id: self.testSuiteId,
                                execution_types: self.executionTypesCollection.models
                            });
                            self.testCaseView.delegateEvents();
                            self.$('#content-main').empty();
                            self.$('#content-main').append(self.testCaseView.el);
                            setTimeout(function() {
                                self.testCaseView.description_simplemde.value(self.testCaseView.model.get('version')['description']);
                                self.testCaseView.description_simplemde.codemirror.refresh();
                            }, 1);
                            setTimeout(function() {
                                self.testCaseView.prerequisite_simplemde.value(self.testCaseView.model.get('version')['prerequisite']);
                                self.testCaseView.prerequisite_simplemde.codemirror.refresh();
                            }, 1);
                        },
                        error: function() {
                            throw new Error('Failure to retrieve executiont types!');
                        }
                    });
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        displayConfirmDeleteTestCase: function() {
            this.displayLoading();
            var self = this;
            this.testCaseModel.set('project_id', this.projectId);
            this.testCaseModel.set('test_suite_id', this.testSuiteId);
            this.testCaseModel.set('id', this.testCaseId);
            this.testCaseModel.fetch({
                success: function(responseData) {
                    self.executionTypesCollection.fetch({
                        success: function() {
                            self.confirmDeleteTestCaseView.render({
                                model: self.testCaseModel,
                                project_id: self.projectId,
                                test_suite_id: self.testSuiteId,
                                execution_types: self.executionTypesCollection.models
                            });
                            self.confirmDeleteTestCaseView.delegateEvents();
                            self.$('#content-main').empty();
                            self.$('#content-main').append(self.confirmDeleteTestCaseView.el);
                        },
                        error: function() {
                            throw new Error('Failure to retrieve executiont types!');
                        }
                    });
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

    });

    return ViewProjectView;

});<|endoftext|>


<commit_before>function randomColor (options) {

  var h,s,v,l,
      rgb, hex, result,
      options = options || {},
      util = loadUtilities();

  // Check if we need to generate mulitple color
  if (options.count) {

    var colors = [],
        totalColors = options.count;
        options.count = false;

    while (colors.length < totalColors) {
      colors.push(randomColor(options))
    }

    return colors
  }

  // First we determine the
  // hue of our random color
  h = pickHue();

  // Returns an array with S and V values
  l = pickLuminosity(h);

  // Split the luminosity array into S and V values
  s = l[0];
  v = l[1];

  // Convert the HSV value to an array representing the color in RGB
  // We do this no matter which format is specified by the user because
  // Hex is a different way of representing a rgb color

  rgb = util.hsvRGB(h,s,v);

  // Represent the rgb color as a hex string
  hex = util.rgbHex(rgb);

  // Set previous hue to improve selection if called again
  randomColor.previousHue = h;

  // Return result in desired format
  switch (options.format) {
    case 'rgb':
      return 'rgb(' + rgb[0] + ', ' + rgb[1] + ', ' + rgb[2]+')'
    case 'rgbArray':
      return rgb;
    case 'hsv':
      return 'hsv(' + h + ', ' + s + ', ' + v +')';
    case 'hsvArray':
      return [h,s,v];
    default:
      return hex
  }

  function pickHue () {

    var hue,
        hueMin = 0,
        hueMax = 360,
        hueRange = [hueMin, hueMax];

    // Determine if there's a preference
    // for the random color's hue
    if (options.hue) {

      // Returns a value or range of values for H
      hue = util.parseHue(options.hue);

      // Determine hue range from parsed hue
      if (typeof hue === 'object') {
        hueRange = hue
      } else if (!hue) {
        hueRange = [hueMin, hueMax]
      } else {
        // hue can only have one possible value
        hueRange = [hue, hue]
      }

      // shift possible H value around the color wheel to contrasting spot
      if (options.hue.contrasts) {
        hueRange = util.shiftHue(hueRange, util.randomBetween(hueMax/2 - 30,hueMax/2 + 30), 'integer');
      }

      // shift possible H value around the color wheel to complementary spot
      if (options.hue.complements) {
        hueRange = util.shiftHue(hueRange, util.randomBetween(hueMax/6 - 30,hueMax/6 + 30), 'integer');
      };

      // pick from within hue range
      return util.randomBetween(hueRange,'integer')

    };

    // If you've already generated a color, let's pick one which is distinct
    if (randomColor.previousHue) {

      do {
        hue = util.randomBetween(hueRange, 'integer');
      } while(Math.abs(hue - randomColor.previousHue) < util.distinctHue)

      return hue
    }

    // No valid hue preference detected, we can pick randomly!

    return util.randomBetween(hueRange,'integer')
  }

  function pickLuminosity (hue) {

    // luminosity is tough to represent as a pair of values but
    // s and v will do for our purposes
    var s,v, sMax, vMax;

    // We look up the color from the randomly generated hue value
    // to determine the s and v values which are attractive
    var colorName = util.lookupColorName(hue),
        color = util.colorDictionary[colorName];

    if (options.luminosity) {

      if (options.luminosity === 'dark') {
        vMax = color.vMin/2 + 50;
        sMax = color.sMin/2 + 50;
      };

      if (options.luminosity === 'dull') {
        vMax = 100;
        sMax = color.sMin/2 + 50;
      };

    } else {
      vMax = 100;
      sMax = 100;
    }

    // Used to plot a line which represents the lower boundary
    // of the attractive triangle
    var m = (100 - color.sMin)/(color.vMin - 100);
        b = color.vMin - m*100;

    // this picks a pair of points in rectangle in the upper right of the hsv color space...
    function newSVpair (log) {
      s = util.randomBetween(color.sMin, sMax,'integer');
      v = util.randomBetween(color.vMin, vMax,'integer');

      if (log) {
        console.log('Constraints: s(' + color.sMin + ', ' + sMax + '), v(' + color.vMin + ', ' + vMax +')');
        console.log('Generated: s(' + s + '), v(' + v + ')');
      }
    }

    // tests if the sv pair lies within the attractive triangle
    function isAttractive () {
      return v < m*s + b
    }

    do {
      newSVpair();
    } while (isAttractive());

    if (options.hue === 'monochrome') {
      // s value needs to be zero to produce a grey
      s = 0;
    }

    return [s,v]

  }
};

function loadUtilities () {
  return {
    goldenRatio: 0.61803398874989,
    distinctHue: 40,
    colorDictionary: {
      red: {
        hueRange: [-26, 18], // oh dear there's also red between 334, 360
        sMin: 47,
        vMin: 70
      },
      orange: {
        hueRange: [18, 46],
        sMin: 40,
        vMin: 83
      },
      yellow: {
        hueRange: [46, 66],
        sMin: 35,
        vMin: 90
      },
      green:  {
        hueRange: [66, 168],
        sMin: 65,
        vMin: 65
      },
      blue: {
        hueRange: [168, 258],
        sMin: 48,
        vMin: 45
        },
      purple: {
        hueRange: [258, 282],
        sMin: 38,
        vMin: 55,
        },
      pink: {
        hueRange: [282, 334],
        sMin: 40,
        vMin: 90
      },
      monochrome: {
        hueRange: [0, 0],
        sMin: 0,
        vMin: 0
      }
    },
    // returns a value, or range of values between 0 and 360
    parseHue: function(colorInput) {

      var rgb,r,g,b,hsv,h,s,v;

      if (typeof colorInput === 'object') {

        if (colorInput.contrasts) {
          return this.parseHue(colorInput.contrasts)
        };

        if (colorInput.complements) {
          return this.parseHue(colorInput.complements)
        };

        if (colorInput.length === 3) {
          return this.rgbHSV(colorInput[0], colorInput[1], colorInput[2])[0];
        };

        return false

      };

      if (typeof colorInput === 'number') {
        return treatAsNumber(colorInput);
      }

      if (typeof colorInput === 'string') {

        if (this.colorDictionary[colorInput]) {
          var color = this.colorDictionary[colorInput];
          return color.hueRange
        }

        if (colorInput === 'previous') {
          return randomColor.previousHue
        }

        // Hex string
        if (colorInput.charAt(0) === '#' & colorInput.length < 8) {
          var rgb = this.hexRGB(colorInput);
          return Math.round((this.rgbHSV(rgb[0], rgb[1], rgb[2])[0] - 0.5)*360);
        };

        // RGB string
        if (colorInput.slice(0,4) === 'rgb(') {
          var rgb = colorInput.slice(4,-1).split(',');
          for (var i in rgb) {
            rgb[i] = parseInt(rgb[i]);
          };

          return Math.round((this.rgbHSV(rgb[0], rgb[1], rgb[2])[0] - 0.5)*360)
        };

        if (typeof parseInt(colorInput) === 'number') {
          return treatAsNumber(parseInt(colorInput))
        }

        return false
      };

      function treatAsNumber (number) {
        if (number < 360 && number > 0) {
          return number
        } else {
          return false
        }
      };

    },
    lookupColorName: function(hue) {

      // Maps red colors to make picking hue easier
      if (hue > 334 && hue < 360) {
        hue-= 360
      };

      for (var colorName in this.colorDictionary) {
         color = this.colorDictionary[colorName];
         if (hue >= color.hueRange[0] &&
             hue <= color.hueRange[1]) {
            return colorName
         }
      } return 'Color not found'
    },
    randomBetween: function(min, max, isInteger) {

      if (typeof min === 'object') {

        var isInteger = max,
            max = min[1],
            min = min[0];

      }

      var number = min + Math.random() * (max - min);
      if (isInteger) {return ~~number};
      return number
    },
    randomPick: function(choices) {
      return choices[Math.floor(Math.random() * choices.length)]
    },
    shiftHue: function(h, degrees) {
      degrees = Math.floor(degrees);
      console.log('shifting b y '+ degrees)
      if (typeof h === "object") {
        for (var key in h) {
          h[key] = (h[key] + degrees)%360
        }
      }

      else if (typeof h === "number") {
        h = (h + degrees)%360
      }

      return h
    },

    rgbHex: function(rgb){

      function componentToHex(c) {
          var hex = c.toString(16);
          return hex.length == 1 ? "0" + hex : hex;
      }

      return "#" + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]);

    },
    hexRGB: function (hex) {
      var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result ? [
        parseInt(result[1], 16),
        parseInt(result[2], 16),
        parseInt(result[3], 16)
      ] : null;
    },
    rgbHSV: function(r,g,b) {

     r /= 255;
     g /= 255;
     b /= 255;

     var max = Math.min.apply( Math, [r,g,b] ),
         min = Math.max.apply( Math, [r,g,b] );

     var h, s, v = max;

     var d = max - min;
     s = max === 0 ? 0 : d / max;

     if(max == min) {
         h = 0; // achromatic
     }
     else {
         switch(max) {
             case r: h = (g - b) / d + (g < b ? 6 : 0); break;
             case g: h = (b - r) / d + 2; break;
             case b: h = (r - g) / d + 4; break;
         }
         h /= 6;
     }
     return [h, s, v]
    },
    hsvRGB: function(h,s,v) {

      // Rebase the h,s,v values
      var h = h/360,
          s = s/100,
          v = v/100;

      var h_i = Math.floor(h*6),
        f = h * 6 - h_i,
        p = v * (1 - s),
        q = v * (1 - f*s),
        t = v * (1 - (1 - f)*s),
        r = 255,
        g = 255,
        b = 255;

      switch(h_i) {
        case 0: r = v, g = t, b = p;  break;
        case 1: r = q, g = v, b = p;  break;
        case 2: r = p, g = v, b = t;  break;
        case 3: r = p, g = q, b = v;  break;
        case 4: r = t, g = p, b = v;  break;
        case 5: r = v, g = p, b = q;  break;
      }
      return [Math.floor(r*256), Math.floor(g*256), Math.floor(b*256)];
    }
  }
};<commit_msg>reorder luminosity<commit_after>function randomColor (options) {

  var h,s,v,l,
      rgb, hex, result,
      options = options || {},
      util = loadUtilities();

  // Check if we need to generate mulitple color
  if (options.count) {

    var colors = [],
        totalColors = options.count;
        options.count = false;

    while (colors.length < totalColors) {
      colors.push(randomColor(options))
    }

    return colors
  }

  // First decide the hue of our color
  h = pickHue();

  // then decide luminosity based on our hue
  l = pickLuminosity(h); // returns [s,v]
  s = l[0];
  v = l[1];

  // Convert the HSV value to an array representing the color in RGB
  // We do this no matter which format is specified by the user because
  // Hex is a different way of representing a rgb color

  rgb = util.hsvRGB(h,s,v);

  // Represent the rgb color as a hex string
  hex = util.rgbHex(rgb);

  // Set previous hue to improve selection if called again
  randomColor.previousHue = h;

  // Return result in desired format
  switch (options.format) {
    case 'rgb':
      return 'rgb(' + rgb[0] + ', ' + rgb[1] + ', ' + rgb[2]+')'
    case 'rgbArray':
      return rgb;
    case 'hsv':
      return 'hsv(' + h + ', ' + s + ', ' + v +')';
    case 'hsvArray':
      return [h,s,v];
    default:
      return hex
  }

  function pickHue () {

    var hue,
        hueMin = 0,
        hueMax = 360,
        hueRange = [hueMin, hueMax];

    // Determine if there's a preference
    // for the random color's hue
    if (options.hue) {

      // Returns a value or range of values for H
      hue = util.parseHue(options.hue);

      // Determine hue range from parsed hue
      if (typeof hue === 'object') {
        hueRange = hue
      } else if (!hue) {
        hueRange = [hueMin, hueMax]
      } else {
        // hue can only have one possible value
        hueRange = [hue, hue]
      }

      // shift possible H value around the color wheel to contrasting spot
      if (options.hue.contrasts) {
        hueRange = util.shiftHue(hueRange, util.randomBetween(hueMax/2 - 30,hueMax/2 + 30), 'integer');
      }

      // shift possible H value around the color wheel to complementary spot
      if (options.hue.complements) {
        hueRange = util.shiftHue(hueRange, util.randomBetween(hueMax/6 - 30,hueMax/6 + 30), 'integer');
      };

      // pick from within hue range
      return util.randomBetween(hueRange,'integer')

    };

    // If you've already generated a color, let's pick one which is distinct
    if (randomColor.previousHue) {

      do {
        hue = util.randomBetween(hueRange, 'integer');
      } while(Math.abs(hue - randomColor.previousHue) < util.distinctHue)

      return hue
    }

    // No valid hue preference detected, we can pick randomly!

    return util.randomBetween(hueRange,'integer')
  }

  function pickLuminosity (hue) {

    // luminosity is tough to represent as a pair of values but
    // s and v will do for our purposes
    var s,v, sMax, vMax;

    // We look up the color from the randomly generated hue value
    // to determine the s and v values which are attractive
    var colorName = util.lookupColorName(hue),
        color = util.colorDictionary[colorName];

    if (options.luminosity) {

      if (options.luminosity === 'dark') {
        vMax = color.vMin/2 + 50;
        sMax = color.sMin/2 + 50;
      };

      if (options.luminosity === 'dull') {
        vMax = 100;
        sMax = color.sMin/2 + 50;
      };

    } else {
      vMax = 100;
      sMax = 100;
    }

    // Used to plot a line which represents the lower boundary
    // of the attractive triangle
    var m = (100 - color.sMin)/(color.vMin - 100);
        b = color.vMin - m*100;

    // this picks a pair of points in rectangle in the upper right of the hsv color space...
    function newSVpair (log) {
      s = util.randomBetween(color.sMin, sMax,'integer');
      v = util.randomBetween(color.vMin, vMax,'integer');

      if (log) {
        console.log('Constraints: s(' + color.sMin + ', ' + sMax + '), v(' + color.vMin + ', ' + vMax +')');
        console.log('Generated: s(' + s + '), v(' + v + ')');
      }
    }

    // tests if the sv pair lies within the attractive triangle
    function isAttractive () {
      return v < m*s + b
    }

    do {
      newSVpair();
    } while (isAttractive());

    if (options.hue === 'monochrome') {
      // s value needs to be zero to produce a grey
      s = 0;
    }

    return [s,v]

  }
};

function loadUtilities () {
  return {
    goldenRatio: 0.61803398874989,
    distinctHue: 40,
    colorDictionary: {
      red: {
        hueRange: [-26, 18], // oh dear there's also red between 334, 360
        sMin: 47,
        vMin: 70
      },
      orange: {
        hueRange: [18, 46],
        sMin: 40,
        vMin: 83
      },
      yellow: {
        hueRange: [46, 66],
        sMin: 35,
        vMin: 90
      },
      green:  {
        hueRange: [66, 168],
        sMin: 65,
        vMin: 65
      },
      blue: {
        hueRange: [168, 258],
        sMin: 48,
        vMin: 45
        },
      purple: {
        hueRange: [258, 282],
        sMin: 38,
        vMin: 55,
        },
      pink: {
        hueRange: [282, 334],
        sMin: 40,
        vMin: 90
      },
      monochrome: {
        hueRange: [0, 0],
        sMin: 0,
        vMin: 0
      }
    },
    // returns a value, or range of values between 0 and 360
    parseHue: function(colorInput) {

      var rgb,r,g,b,hsv,h,s,v;

      if (typeof colorInput === 'object') {

        if (colorInput.contrasts) {
          return this.parseHue(colorInput.contrasts)
        };

        if (colorInput.complements) {
          return this.parseHue(colorInput.complements)
        };

        if (colorInput.length === 3) {
          return this.rgbHSV(colorInput[0], colorInput[1], colorInput[2])[0];
        };

        return false

      };

      if (typeof colorInput === 'number') {
        return treatAsNumber(colorInput);
      }

      if (typeof colorInput === 'string') {

        if (this.colorDictionary[colorInput]) {
          var color = this.colorDictionary[colorInput];
          return color.hueRange
        }

        if (colorInput === 'previous') {
          return randomColor.previousHue
        }

        // Hex string
        if (colorInput.charAt(0) === '#' & colorInput.length < 8) {
          var rgb = this.hexRGB(colorInput);
          return Math.round((this.rgbHSV(rgb[0], rgb[1], rgb[2])[0] - 0.5)*360);
        };

        // RGB string
        if (colorInput.slice(0,4) === 'rgb(') {
          var rgb = colorInput.slice(4,-1).split(',');
          for (var i in rgb) {
            rgb[i] = parseInt(rgb[i]);
          };

          return Math.round((this.rgbHSV(rgb[0], rgb[1], rgb[2])[0] - 0.5)*360)
        };

        if (typeof parseInt(colorInput) === 'number') {
          return treatAsNumber(parseInt(colorInput))
        }

        return false
      };

      function treatAsNumber (number) {
        if (number < 360 && number > 0) {
          return number
        } else {
          return false
        }
      };

    },
    lookupColorName: function(hue) {

      // Maps red colors to make picking hue easier
      if (hue > 334 && hue < 360) {
        hue-= 360
      };

      for (var colorName in this.colorDictionary) {
         color = this.colorDictionary[colorName];
         if (hue >= color.hueRange[0] &&
             hue <= color.hueRange[1]) {
            return colorName
         }
      } return 'Color not found'
    },
    randomBetween: function(min, max, isInteger) {

      if (typeof min === 'object') {

        var isInteger = max,
            max = min[1],
            min = min[0];

      }

      var number = min + Math.random() * (max - min);
      if (isInteger) {return ~~number};
      return number
    },
    randomPick: function(choices) {
      return choices[Math.floor(Math.random() * choices.length)]
    },
    shiftHue: function(h, degrees) {
      degrees = Math.floor(degrees);
      console.log('shifting b y '+ degrees)
      if (typeof h === "object") {
        for (var key in h) {
          h[key] = (h[key] + degrees)%360
        }
      }

      else if (typeof h === "number") {
        h = (h + degrees)%360
      }

      return h
    },

    rgbHex: function(rgb){

      function componentToHex(c) {
          var hex = c.toString(16);
          return hex.length == 1 ? "0" + hex : hex;
      }

      return "#" + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]);

    },
    hexRGB: function (hex) {
      var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result ? [
        parseInt(result[1], 16),
        parseInt(result[2], 16),
        parseInt(result[3], 16)
      ] : null;
    },
    rgbHSV: function(r,g,b) {

     r /= 255;
     g /= 255;
     b /= 255;

     var max = Math.min.apply( Math, [r,g,b] ),
         min = Math.max.apply( Math, [r,g,b] );

     var h, s, v = max;

     var d = max - min;
     s = max === 0 ? 0 : d / max;

     if(max == min) {
         h = 0; // achromatic
     }
     else {
         switch(max) {
             case r: h = (g - b) / d + (g < b ? 6 : 0); break;
             case g: h = (b - r) / d + 2; break;
             case b: h = (r - g) / d + 4; break;
         }
         h /= 6;
     }
     return [h, s, v]
    },
    hsvRGB: function(h,s,v) {

      // Rebase the h,s,v values
      var h = h/360,
          s = s/100,
          v = v/100;

      var h_i = Math.floor(h*6),
        f = h * 6 - h_i,
        p = v * (1 - s),
        q = v * (1 - f*s),
        t = v * (1 - (1 - f)*s),
        r = 255,
        g = 255,
        b = 255;

      switch(h_i) {
        case 0: r = v, g = t, b = p;  break;
        case 1: r = q, g = v, b = p;  break;
        case 2: r = p, g = v, b = t;  break;
        case 3: r = p, g = q, b = v;  break;
        case 4: r = t, g = p, b = v;  break;
        case 5: r = v, g = p, b = q;  break;
      }
      return [Math.floor(r*256), Math.floor(g*256), Math.floor(b*256)];
    }
  }
};<|endoftext|>


<commit_before>/***
 Hawk Main Script
 ***/
'use strict';

/* Hawk Main Module */
angular
    .module("hawk", [
        "hawk.environmentsManagement",
        "hawk.agentsManagement",
        "hawk.pipelinesManagement",
        "hawk.userManagement",
        "hawk.adminManagement",
        "hawk.profileManagement",
        "ui.router",
        'ui.sortable',
        "ui.bootstrap",
        //"oc.lazyLoad",
        //"ngSanitize",
        'luegg.directives',
        'toaster',
        'momentjs',
        'satellizer',
        'ansi_up'
        //'ngAnimate'
        //'flow'
    ])

    .constant({
        CONSTANTS: {
            'BASE_URL': '/api',
            'WS_URL': 'ws://hawkserver:8080/ws/v1',
            'CONFIG': '/config',
            'EXEC': '/exec',
            'STATS': '/stats',
            'PIPELINES': '/pipelines',
            'PIPELINE_GROUPS': "/pipeline_groups",
            'AGENTS': '/agents',
            'STAGES': '/stages',
            'JOBS': '/jobs',
            'TASKS': '/tasks',
            'ARTIFACTS': '/artifacts',
            'MATERIALS': '/materials',
            'SERVER': '/server',
            'ENVIRONMENTS': '/environments',
            'ENVIRONMENTVARS': '/environmentvariables',
            'ACCOUNT': '/Account',
            'USERS': '/Users',
            'DEV': '/dev',

            'MODEL': 'net.hawkengine.model',
            'SERVICES': 'net.hawkengine.services',

            //region agent methods
            'AGENT_GET_BY_ID': 'getAgentById',
            'AGENT_GET_ALL': 'getAllAgents',
            'AGENT_ADD': 'addAgent',
            'AGENT_UPDATE': 'updateAgent',
            'AGENT_DELETE': 'deleteAgent',
            'AGENT_SET_CONFIGSTATE': 'setAgentConfigState',
            //endregion

            //region agent packages
            'AGENT_SERVICE': 'AgentService',
            'AGENT_MODEL': 'Agent'
            //endregion
        }
    })

    /* Setup global settings */
    .factory('settings', ['$rootScope', function ($rootScope) {
        // supported languages
        var settings = {
            layout: {

                pageContentWhite: true, // set page content layout
                pageBodySolid: false, // solid body color state
                pageAutoScrollOnLoad: 1000 // auto scroll to top on page load
            },
            assetsPath: '../assets',
            globalPath: '../assets/global',
            layoutPath: '../assets/layouts/layout'
        };

        $rootScope.settings = settings;

        return settings;
    }])

    /* Setup Routing For All Pages */
    .config(['$stateProvider', '$urlRouterProvider', '$animateProvider','$authProvider',
            function ($stateProvider, $urlRouterProvider, $animateProvider, $authProvider) {

             // used for debugging
             $authProvider.baseUrl = "http://localhost:8080";
             $authProvider.github({
                  clientId: '2d3dbbf586d2260cbd68',
                  scope: ['user:email','repo']
                });

        // Redirect any unmatched url
        $urlRouterProvider.otherwise("/");
        //$animateProvider.classNameFilter(/angular-animate/);
        $stateProvider
            .state('auth', {
                url: "/authenticate",
                templateUrl: "app/auth.html",
                data: {
                    pageTitle: 'Authenticate'
                },
                resolve: {
                    auth: function (authDataService, pipeStatsService, agentService, $location) {
                        if (authDataService.authenticationData.IsAuthenticated) {
                            //pipeStatsService.getAgentById();
                            //$location.path('/pipelines');
                        }
                    }
                }
            })

            .state('index', {
                url: "/",
                templateUrl: "app/main.html",
                resolve: {
                    auth: function (authDataService, pipeStatsService, agentService, $location,
                    $auth, $rootScope, $timeout) {

                        console.log("isAuthenticated: "+ $auth.isAuthenticated());

                        if(!$auth.isAuthenticated()){
                            $timeout(function(){
                                 $location.path('/authenticate');
                                 $rootScope.$apply();
                            }, 100);
                        }

                        //$auth.authenticate('github');

                        if (!authDataService.authenticationData.IsAuthenticated) {
                            //pipeStatsService.getAgentById();
                            //$location.path('/authenticate');
                        }
                    }
                }
            })

    }])

    /* Init global settings and run the app */
    .run(["$rootScope", "settings", "$state", "websocketReceiverService", "agentService", "adminGroupService", "adminService", "adminMaterialService", "pipeConfigService", "pipeExecService", "authenticationService", "toaster", "$auth", "$location", function ($rootScope, settings, $state, websocketReceiverService, agentService, adminGroupService, adminService, adminMaterialService, pipeConfigService, pipeExecService, authenticationService, toaster, $auth, $location) {
        $rootScope.$state = $state; // state to be accessed from view
        $rootScope.$settings = settings; // state to be accessed from view
        $rootScope.$on('$stateChange');

        var wsServerLocation = "ws://hawkserver:8080/ws/v1";

        var timerID=0;

        //TODO: Replace localStorage with $auth.isAuthenitcated()
        $rootScope.startWebsocket = function start(wsServerLocation){
            $rootScope.socket = new WebSocket(wsServerLocation.concat('?token=' + $auth.getToken()));

            $rootScope.socket.onmessage = function (event) {
                console.log(event.data);
                websocketReceiverService.processEvent(JSON.parse(event.data));
            };

            $rootScope.socket.onopen = function (event) {
                toaster.clear();
                toaster.pop('success', "Notification", "Connection to server successful!");
                if(window.timerID){
                    window.clearInterval(window.timerID);
                    window.timerID=0;
                }

                // pipeConfigService.getAllJobDefinitions();
                // pipeConfigService.getAllStageDefinitions();
                //pipeStatsService.getAgentById();

                //adminGroupService.getAllPipelineGroups();
                pipeConfigService.getAllPipelineDefinitions();
                pipeConfigService.getAllPipelineGroupDTOs();
                agentService.getAllAgents();
                pipeExecService.getAllPipelines();
                adminService.getAllUserGroupDTOs();
                adminService.getAllUsers();
                //adminMaterialService.getAllMaterialDefinitions();
            };

            $rootScope.socket.onclose = function (event) {
                if(!$auth.isAuthenticated()){
                    $auth.logout();
                    $location.path('/authenticate');
                    console.log(event);
                    toaster.pop('error', "Notification", event.reason);
                    $rootScope.$apply();
                    return;
                }
                if(!window.timerID){
                    window.timerID=setInterval(function(){start(wsServerLocation)}, 5000);
                }

                toaster.clear();
                toaster.pop('error', "Notification", "Connection lost. Reconnecting...", 0);
                $rootScope.$apply();
            }
        };
        //debugger;
        if($auth.isAuthenticated()){
            $rootScope.startWebsocket(wsServerLocation);
            console.log($auth.getToken());
        }

    }]);

/* Fix for Bootstrap modal behavior */
window.onhashchange = function () {
    $('.modal-backdrop').remove();
};
<commit_msg>Fixed routing of pages and set default page to /pipelines<commit_after>/***
 Hawk Main Script
 ***/
'use strict';

/* Hawk Main Module */
angular
    .module("hawk", [
        "hawk.environmentsManagement",
        "hawk.agentsManagement",
        "hawk.pipelinesManagement",
        "hawk.userManagement",
        "hawk.adminManagement",
        "hawk.profileManagement",
        "ui.router",
        'ui.sortable',
        "ui.bootstrap",
        //"oc.lazyLoad",
        //"ngSanitize",
        'luegg.directives',
        'toaster',
        'momentjs',
        'satellizer',
        'ansi_up'
        //'ngAnimate'
        //'flow'
    ])

    .constant({
        CONSTANTS: {
            'BASE_URL': '/api',
            'WS_URL': 'ws://hawkserver:8080/ws/v1',
            'CONFIG': '/config',
            'EXEC': '/exec',
            'STATS': '/stats',
            'PIPELINES': '/pipelines',
            'PIPELINE_GROUPS': "/pipeline_groups",
            'AGENTS': '/agents',
            'STAGES': '/stages',
            'JOBS': '/jobs',
            'TASKS': '/tasks',
            'ARTIFACTS': '/artifacts',
            'MATERIALS': '/materials',
            'SERVER': '/server',
            'ENVIRONMENTS': '/environments',
            'ENVIRONMENTVARS': '/environmentvariables',
            'ACCOUNT': '/Account',
            'USERS': '/Users',
            'DEV': '/dev',

            'MODEL': 'net.hawkengine.model',
            'SERVICES': 'net.hawkengine.services',

            //region agent methods
            'AGENT_GET_BY_ID': 'getAgentById',
            'AGENT_GET_ALL': 'getAllAgents',
            'AGENT_ADD': 'addAgent',
            'AGENT_UPDATE': 'updateAgent',
            'AGENT_DELETE': 'deleteAgent',
            'AGENT_SET_CONFIGSTATE': 'setAgentConfigState',
            //endregion

            //region agent packages
            'AGENT_SERVICE': 'AgentService',
            'AGENT_MODEL': 'Agent'
            //endregion
        }
    })

    /* Setup global settings */
    .factory('settings', ['$rootScope', function ($rootScope) {
        // supported languages
        var settings = {
            layout: {

                pageContentWhite: true, // set page content layout
                pageBodySolid: false, // solid body color state
                pageAutoScrollOnLoad: 1000 // auto scroll to top on page load
            },
            assetsPath: '../assets',
            globalPath: '../assets/global',
            layoutPath: '../assets/layouts/layout'
        };

        $rootScope.settings = settings;

        return settings;
    }])

    /* Setup Routing For All Pages */
    .config(['$stateProvider', '$urlRouterProvider', '$animateProvider','$authProvider',
            function ($stateProvider, $urlRouterProvider, $animateProvider, $authProvider) {

             // used for debugging
             $authProvider.baseUrl = "http://localhost:8080";
             $authProvider.github({
                  clientId: '2d3dbbf586d2260cbd68',
                  scope: ['user:email','repo']
                });

        // Redirect any unmatched url
        $urlRouterProvider.when('', '/pipelines').when('/', '/pipelines').otherwise("/pipelines");
        //$animateProvider.classNameFilter(/angular-animate/);
        $stateProvider
            .state('auth', {
                url: "/authenticate",
                templateUrl: "app/auth.html",
                data: {
                    pageTitle: 'Authenticate'
                },
                resolve: {
                    auth: function (authDataService, pipeStatsService, agentService, $location) {
                        if (authDataService.authenticationData.IsAuthenticated) {
                            //pipeStatsService.getAgentById();
                            // $location.path('/pipelines');
                        }
                    }
                }
            })

            .state('index', {
                url: "/",
                templateUrl: "app/main.html",
                resolve: {
                    auth: function (authDataService, pipeStatsService, agentService, $location,
                    $auth, $rootScope, $timeout) {

                        console.log("isAuthenticated: "+ $auth.isAuthenticated());

                        if(!$auth.isAuthenticated()){
                            $timeout(function(){
                                 $location.path('/authenticate');
                                 $rootScope.$apply();
                            }, 100);
                        }

                        //$auth.authenticate('github');

                        if (!authDataService.authenticationData.IsAuthenticated) {
                            //pipeStatsService.getAgentById();
                            //$location.path('/authenticate');
                        }
                    }
                }
            })

    }])

    /* Init global settings and run the app */
    .run(["$rootScope", "settings", "$state", "websocketReceiverService", "agentService", "adminGroupService", "adminService", "adminMaterialService", "pipeConfigService", "pipeExecService", "authenticationService", "toaster", "$auth", "$location", function ($rootScope, settings, $state, websocketReceiverService, agentService, adminGroupService, adminService, adminMaterialService, pipeConfigService, pipeExecService, authenticationService, toaster, $auth, $location) {
        $rootScope.$state = $state; // state to be accessed from view
        $rootScope.$settings = settings; // state to be accessed from view
        $rootScope.$on('$stateChange');

        var wsServerLocation = "ws://hawkserver:8080/ws/v1";

        var timerID=0;

        //TODO: Replace localStorage with $auth.isAuthenitcated()
        $rootScope.startWebsocket = function start(wsServerLocation){
            $rootScope.socket = new WebSocket(wsServerLocation.concat('?token=' + $auth.getToken()));

            $rootScope.socket.onmessage = function (event) {
                console.log(event.data);
                websocketReceiverService.processEvent(JSON.parse(event.data));
            };

            $rootScope.socket.onopen = function (event) {
                toaster.clear();
                toaster.pop('success', "Notification", "Connection to server successful!");
                if(window.timerID){
                    window.clearInterval(window.timerID);
                    window.timerID=0;
                }

                // pipeConfigService.getAllJobDefinitions();
                // pipeConfigService.getAllStageDefinitions();
                //pipeStatsService.getAgentById();

                //adminGroupService.getAllPipelineGroups();
                pipeConfigService.getAllPipelineDefinitions();
                pipeConfigService.getAllPipelineGroupDTOs();
                agentService.getAllAgents();
                pipeExecService.getAllPipelines();
                adminService.getAllUserGroupDTOs();
                adminService.getAllUsers();
                //adminMaterialService.getAllMaterialDefinitions();
            };

            $rootScope.socket.onclose = function (event) {
                if(!$auth.isAuthenticated()){
                    $auth.logout();
                    $location.path('/authenticate');
                    console.log(event);
                    toaster.pop('error', "Notification", event.reason);
                    $rootScope.$apply();
                    return;
                }
                if(!window.timerID){
                    window.timerID=setInterval(function(){start(wsServerLocation)}, 5000);
                }

                toaster.clear();
                toaster.pop('error', "Notification", "Connection lost. Reconnecting...", 0);
                $rootScope.$apply();
            }
        };
        //debugger;
        if($auth.isAuthenticated()){
            $rootScope.startWebsocket(wsServerLocation);
            console.log($auth.getToken());
        }

    }]);

/* Fix for Bootstrap modal behavior */
window.onhashchange = function () {
    $('.modal-backdrop').remove();
};
<|endoftext|>


<commit_before>'use strict';

angular.module('playApp.hdkeys', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/hdkeys', {
    templateUrl: 'hdkeys/hdkeys.html',
    controller: 'HDKeysCtrl'
  });
}])

.controller('HDKeysCtrl', function($scope) {
  $scope.path = 'm/817/6023';
  $scope.keys = [];

  $scope.$on('networkUpdate', function() {
    $scope.newKey();
  });

  $scope.serialize = function() {
    return JSON.stringify({
      network: bitcore.Networks.defaultNetwork.name,
      xpriv: $scope.xpriv,
      xpub: $scope.xpub,
      path: $scope.path
    });
  };

  $scope.newKey = function() {
    $scope.updatePrivate(new bitcore.HDPrivateKey().toString());
  };

  $scope.updatePrivate = function(value) {
    if (!bitcore.HDPrivateKey.isValidSerialized(value)) return; // mark as invalid

    $scope.xpriv = new bitcore.HDPrivateKey(value);
    $scope.xpub = $scope.xpriv.hdPublicKey;
    $scope.keys = $scope.deriveKeys($scope.xpriv, $scope.path);
    setExampleCode($scope.xpriv, $scope.path);
  };

  $scope.updatePublic = function(value) {
    if (!bitcore.HDPublicKey.isValidSerialized(value)) return; // mark as invalid

    $scope.xpriv = '';
    $scope.xpub = new bitcore.HDPublicKey(value);
    $scope.keys = $scope.deriveKeys($scope.xpub, $scope.path);
    setExampleCode($scope.xpub, $scope.path);
  };

  $scope.updatePath = function(value) {
    if (!bitcore.HDPrivateKey.isValidPath(value)) return; // mark as invalid

    $scope.keys = $scope.deriveKeys($scope.xpriv || $scope.xpub, value);
    setExampleCode($scope.xpriv || $scope.xpub, value);
  };

  $scope.deriveKeys = function(key, path) {
    var xpriv, xpub;
    if (key instanceof bitcore.HDPrivateKey) {
      xpriv = key;
      xpub = key.hdPublicKey;
    } else if (key instanceof bitcore.HDPublicKey) {
      xpriv = null;
      xpub = key;
    } else {
      return;
    }

    // TODO: Check validation path on public key as well
    if (!bitcore.HDPrivateKey.isValidPath(path)) return;

    var indexes = bitcore.HDPrivateKey._getDerivationIndexes(path);
    var paths = indexes.map(function(m, i) {
      return 'm/' + indexes.slice(0, i+1).join('/');
    });
    paths = ['m'].concat(paths);

    var nodes = paths.map(function(p) {
      return {
        path: p,
        xpriv: xpriv && key.derive(p),
        xpub: key.derive(p).hdPublicKey
      }
    });

    nodes[nodes.length-1].visible = true;
    return nodes;
  }

  function setExampleCode(hdKey, path, isNew) {
    var template = "";

    if (hdKey instanceof bitcore.HDPublicKey) {
      template += "var hdPublicKey = new bitcore.HDPrivateKey();\n";
      template += "var derivedHdPublicKey = hdPublicKey.derive('" + path + "');\n"

    } else if (hdKey instanceof bitcore.HDPrivateKey) {
      template += "var hdPrivateKey = new bitcore.HDPrivateKey();\n";

      template += "\n// private key derivation\n";
      template += "var derivedHdPrivateKey = hdPrivateKey.derive('" + path + "');\n"
      template += "var derivedPrivateKey = hdPrivateKey.privateKey;\n"

      template += "\n// public key derivation\n";
      template += "var derivedHdPublicKey = derivedHdPrivateKey.hdPublicKey;\n"
    }

    template += "var derivedPublicKey = derivedHdPublicKey.publicKey;\n"
    template += "var address = derivedPublicKey.toAddress();\n"

    $scope.exampleCode = template;
  };

  $scope.newKey();
});<commit_msg>Show the hardened paths with a quote instead of a large number<commit_after>'use strict';

angular.module('playApp.hdkeys', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/hdkeys', {
    templateUrl: 'hdkeys/hdkeys.html',
    controller: 'HDKeysCtrl'
  });
}])

.controller('HDKeysCtrl', function($scope) {
  $scope.path = 'm/817/6023';
  $scope.keys = [];

  $scope.$on('networkUpdate', function() {
    $scope.newKey();
  });

  $scope.serialize = function() {
    return JSON.stringify({
      network: bitcore.Networks.defaultNetwork.name,
      xpriv: $scope.xpriv,
      xpub: $scope.xpub,
      path: $scope.path
    });
  };

  $scope.newKey = function() {
    $scope.updatePrivate(new bitcore.HDPrivateKey().toString());
  };

  $scope.updatePrivate = function(value) {
    if (!bitcore.HDPrivateKey.isValidSerialized(value)) return; // mark as invalid

    $scope.xpriv = new bitcore.HDPrivateKey(value);
    $scope.xpub = $scope.xpriv.hdPublicKey;
    $scope.keys = $scope.deriveKeys($scope.xpriv, $scope.path);
    setExampleCode($scope.xpriv, $scope.path);
  };

  $scope.updatePublic = function(value) {
    if (!bitcore.HDPublicKey.isValidSerialized(value)) return; // mark as invalid

    $scope.xpriv = '';
    $scope.xpub = new bitcore.HDPublicKey(value);
    $scope.keys = $scope.deriveKeys($scope.xpub, $scope.path);
    setExampleCode($scope.xpub, $scope.path);
  };

  $scope.updatePath = function(value) {
    if (!bitcore.HDPrivateKey.isValidPath(value)) return; // mark as invalid

    $scope.keys = $scope.deriveKeys($scope.xpriv || $scope.xpub, value);
    setExampleCode($scope.xpriv || $scope.xpub, value);
  };

  $scope.deriveKeys = function(key, path) {
    var xpriv, xpub;
    if (key instanceof bitcore.HDPrivateKey) {
      xpriv = key;
      xpub = key.hdPublicKey;
    } else if (key instanceof bitcore.HDPublicKey) {
      xpriv = null;
      xpub = key;
    } else {
      return;
    }

    // TODO: Check validation path on public key as well
    if (!bitcore.HDPrivateKey.isValidPath(path)) return;

    var indexes = bitcore.HDPrivateKey._getDerivationIndexes(path);
    var MAX = 2147483647;
    var paths = indexes.map(function(m, i) {
      return 'm/' + indexes.slice(0, i+1).map(function(index) {
        if (index >= MAX) {
          return (index - MAX) + "'";
        }
        return '' + index;
      }).join('/');
    });
    paths = ['m'].concat(paths);

    var nodes = paths.map(function(p) {
      return {
        path: p,
        xpriv: xpriv && key.derive(p),
        xpub: key.derive(p).hdPublicKey
      };
    });

    nodes[nodes.length-1].visible = true;
    return nodes;
  };

  function setExampleCode(hdKey, path, isNew) {
    var template = "";

    if (hdKey instanceof bitcore.HDPublicKey) {
      template += "var hdPublicKey = new bitcore.HDPrivateKey();\n";
      template += "var derivedHdPublicKey = hdPublicKey.derive('" + path + "');\n"

    } else if (hdKey instanceof bitcore.HDPrivateKey) {
      template += "var hdPrivateKey = new bitcore.HDPrivateKey();\n";

      template += "\n// private key derivation\n";
      template += "var derivedHdPrivateKey = hdPrivateKey.derive('" + path + "');\n"
      template += "var derivedPrivateKey = hdPrivateKey.privateKey;\n"

      template += "\n// public key derivation\n";
      template += "var derivedHdPublicKey = derivedHdPrivateKey.hdPublicKey;\n"
    }

    template += "var derivedPublicKey = derivedHdPublicKey.publicKey;\n"
    template += "var address = derivedPublicKey.toAddress();\n"

    $scope.exampleCode = template;
  };

  $scope.newKey();
});
<|endoftext|>


<commit_before>/*
 * Spark Model
 */

define(['core/models/program'], function (Program) {

    var METRICS_PATHS = {
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.BlockManager.memory.remainingMem_MB?aggregate=true': 'blockRemainingMemory',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.BlockManager.memory.maxMem_MB?aggregate=true': 'blockMaxMemory',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.BlockManager.memory.memUsed_MB?aggregate=true': 'blockUsedMemory',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.BlockManager.disk.diskSpaceUsed_MB?aggregate=true': 'blockDiskSpaceUsed',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.job.activeJobs?aggregate=true': 'schedulerActiveJobs',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.job.allJobs?aggregate=true': 'schedulerAllJobs',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.stage.failedStages?aggregate=true': 'schedulerFailedStages',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.stage.runningStages?aggregate=true': 'schedulerRunningStages',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.stage.waitingStages?aggregate=true': 'schedulerWaitingStages'
    };

    var METRIC_TYPES = {
        'blockRemainingMemory': 'number',
        'blockMaxMemory': 'number',
        'blockUsedMemory': 'number',
        'blockDiskSpaceUsed': 'number',
        'schedulerActiveJobs': 'number',
        'schedulerAllJobs': 'number',
        'schedulerFailedStages': 'number',
        'schedulerRunningStages': 'number',
        'schedulerWaitingStages': 'number'
    };

    var EXPECTED_FIELDS = [
        'name',
        'description'
    ];

    var Model = Program.extend({
        type: 'Spark',
        plural: 'Spark',
        href: function () {
            return '#/spark/' + this.get('id');
        }.property('id'),

        currentState: '',

        init: function () {
            this._super();
            this.set('id', this.get('app') + ':' + this.get('name'));
            this.set('description', this.get('meta') || 'Spark');
            if (this.get('meta')) {
                this.set('startTime', this.get('meta').startTime);
            }

            this.set("metricsData", Em.Object.create({
                blockRemainingMemory: 0,
                blockMaxMemory: 0,
                blockUsedMemory: 0,
                blockDiskSpaceUsed: 0,
                schedulerActiveJobs: 0,
                schedulerAllJobs: 0,
                schedulerFailedStages: 0,
                schedulerRunningStages: 0,
                schedulerWaitingStages: 0
            }));
        },

        start: function (http) {
            var model = this;
            model.set('currentState', 'STARTING');

            http.post('rest', 'apps', this.get('app'), 'spark', model.get('name'), 'start',
                function (response) {

                    if (response.error) {
                        C.Modal.show(response.error, response.message);
                    } else {
                        model.set('lastStarted', new Date().getTime() / 1000);
                    }

                });
        },

        stop: function (http) {
            var model = this;
            model.set('currentState', 'STOPPING');

            http.post('rest', 'apps', this.get('app'), 'spark', model.get('name'), 'stop',
                function (response) {

                    if (response.error) {
                        C.Modal.show(response.error, response.message);
                    } else {
                        model.set('lastStarted', new Date().getTime() / 1000);
                    }

                });
        },

        getStartDate: function () {
            var time = parseInt(this.get('startTime'), 10);
            return new Date(time).toString('MMM d, yyyy');
        }.property('startTime'),

        getStartHours: function () {
            var time = parseInt(this.get('startTime'), 10);
            return new Date(time).toString('hh:mm tt');
        }.property('startTime'),

        context: function () {

            return this.interpolate('apps/{parent}/spark/{id}');

        }.property('app', 'name'),

        interpolate: function (path) {

            return path.replace(/\{parent\}/, this.get('app'))
                .replace(/\{id\}/, this.get('name'));

        },

        startStopDisabled: function () {

            if (this.currentState === 'STARTING' ||
                this.currentState === 'STOPPING') {
                return true;
            }

            return false;

        }.property('currentState'),

        getMetricsRequest: function (http) {
            var self = this;
            var appId = this.get('app');
            var programId = this.get('id');
            var paths = [];
            var pathMap = {};
            for (var path in METRICS_PATHS) {
                var url = new S(path).template({'appId': appId, 'programId': programId}).s;
                paths.push(url);
                pathMap[url] = METRICS_PATHS[path];
            }
            http.post('metrics', paths, function (response, status) {
                if (!response.result) {
                    return;
                }
                var result = response.result;
                var i = result.length, metric;
                while (i--) {
                    metric = pathMap[result[i]['path']];
                    if (metric) {
                        if (result[i]['result']['data'] instanceof Array) {
                            result[i]['result']['data'] = result[i]['result']['data'].map(function (entry) {
                                return entry.value;
                            });
                            self.setMetricData(metric, result[i]['result']['data']);
                        }
                        else if (METRIC_TYPES[metric] === 'number') {
                            self.setMetricData(metric, C.Util.numberArrayToString(result[i]['result']['data']));
                        } else {
                            self.setMetricData(metric, result[i]['result']['data']);
                        }
                    }
                    metric = null;
                }
            });
        },

        setMetricData: function (name, value) {
            var metricsData = this.get('metricsData');
            //todo remove it when services will be fixed
            //never zero
            if (value == 0)
                value = Math.floor((Math.random() * 30) + 1);
            metricsData.set(name, value);
        }
    });

    Model.reopenClass({
        type: 'Spark',
        kind: 'Model',
        find: function (model_id, http) {

            model_id = model_id.split(':');

            var self = this,
                promise = Ember.Deferred.create(),
                app_id = model_id[0],
                spark_id = model_id[1];

            http.rest('apps', app_id, 'spark', spark_id, function (model, error) {

                model = self.transformModel(model);

                model.app = app_id;
                model = C.Spark.create(model);
                model.id = spark_id;
                model.name = spark_id;

                http.rest('apps', app_id, 'spark', spark_id, 'status', function (response) {
                    if (!$.isEmptyObject(response)) {
                        model.set('currentState', response.status);
                        promise.resolve(model);
                    } else {
                        promise.reject('Status not found');
                    }
                });

            });

            return promise;
        },

        transformModel: function (model) {

            var newModel = {};
            for (var i = EXPECTED_FIELDS.length - 1; i >= 0; i--) {
                newModel[EXPECTED_FIELDS[i]] = model[EXPECTED_FIELDS[i]];
            }
            if ('appId' in model || 'applicationId' in model) {
                newModel.appId = model.appId || model.applicationId;
            }
            return newModel;

        }
    });

    return Model;

});<commit_msg>fixed comments<commit_after>/*
 * Spark Model
 */

define(['core/models/program'], function (Program) {

    var METRICS_PATHS = {
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.BlockManager.memory.remainingMem_MB?aggregate=true': 'blockRemainingMemory',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.BlockManager.memory.maxMem_MB?aggregate=true': 'blockMaxMemory',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.BlockManager.memory.memUsed_MB?aggregate=true': 'blockUsedMemory',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.BlockManager.disk.diskSpaceUsed_MB?aggregate=true': 'blockDiskSpaceUsed',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.job.activeJobs?aggregate=true': 'schedulerActiveJobs',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.job.allJobs?aggregate=true': 'schedulerAllJobs',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.stage.failedStages?aggregate=true': 'schedulerFailedStages',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.stage.runningStages?aggregate=true': 'schedulerRunningStages',
        'system/apps/{{appId}}/spark/{{programId}}/{{programId}}.DAGScheduler.stage.waitingStages?aggregate=true': 'schedulerWaitingStages'
    };

    var METRIC_TYPES = {
        'blockRemainingMemory': 'number',
        'blockMaxMemory': 'number',
        'blockUsedMemory': 'number',
        'blockDiskSpaceUsed': 'number',
        'schedulerActiveJobs': 'number',
        'schedulerAllJobs': 'number',
        'schedulerFailedStages': 'number',
        'schedulerRunningStages': 'number',
        'schedulerWaitingStages': 'number'
    };

    var EXPECTED_FIELDS = [
        'name',
        'description'
    ];

    var Model = Program.extend({
        type: 'Spark',
        plural: 'Spark',
        href: function () {
            return '#/spark/' + this.get('id');
        }.property('id'),

        currentState: '',

        init: function () {
            this._super();
            this.set('id', this.get('app') + ':' + this.get('name'));
            this.set('description', this.get('meta') || 'Spark');
            if (this.get('meta')) {
                this.set('startTime', this.get('meta').startTime);
            }

            this.set("metricsData", Em.Object.create({
                blockRemainingMemory: 0,
                blockMaxMemory: 0,
                blockUsedMemory: 0,
                blockDiskSpaceUsed: 0,
                schedulerActiveJobs: 0,
                schedulerAllJobs: 0,
                schedulerFailedStages: 0,
                schedulerRunningStages: 0,
                schedulerWaitingStages: 0
            }));
        },

        start: function (http) {
            var model = this;
            model.set('currentState', 'STARTING');

            http.post('rest', 'apps', this.get('app'), 'spark', model.get('name'), 'start',
                function (response) {

                    if (response.error) {
                        C.Modal.show(response.error, response.message);
                    } else {
                        model.set('lastStarted', new Date().getTime() / 1000);
                    }

                });
        },

        stop: function (http) {
            var model = this;
            model.set('currentState', 'STOPPING');

            http.post('rest', 'apps', this.get('app'), 'spark', model.get('name'), 'stop',
                function (response) {

                    if (response.error) {
                        C.Modal.show(response.error, response.message);
                    } else {
                        model.set('lastStarted', new Date().getTime() / 1000);
                    }

                });
        },

        getStartDate: function () {
            var time = parseInt(this.get('startTime'), 10);
            return new Date(time).toString('MMM d, yyyy');
        }.property('startTime'),

        getStartHours: function () {
            var time = parseInt(this.get('startTime'), 10);
            return new Date(time).toString('hh:mm tt');
        }.property('startTime'),

        context: function () {

            return this.interpolate('apps/{parent}/spark/{id}');

        }.property('app', 'name'),

        interpolate: function (path) {

            return path.replace(/\{parent\}/, this.get('app'))
                .replace(/\{id\}/, this.get('name'));

        },

        startStopDisabled: function () {

            if (this.currentState === 'STARTING' ||
                this.currentState === 'STOPPING') {
                return true;
            }

            return false;

        }.property('currentState'),

        getMetricsRequest: function (http) {
            var self = this;
            var appId = this.get('app');
            var programId = this.get('id');
            var paths = [];
            var pathMap = {};
            for (var path in METRICS_PATHS) {
                var url = new S(path).template({'appId': appId, 'programId': programId}).s;
                paths.push(url);
                pathMap[url] = METRICS_PATHS[path];
            }
            http.post('metrics', paths, function (response, status) {
                if (!response.result) {
                    return;
                }
                var result = response.result;
                var i = result.length, metric;
                while (i--) {
                    metric = pathMap[result[i]['path']];
                    if (metric) {
                        var res = result[i]['result'];
                        if (res) {
                            var respData = res['data'];
                            if (respData instanceof Array) {
                                res['data'] = respData.map(function (entry) {
                                    return entry.value;
                                });
                                self.setMetricData(metric, respData);
                            }
                            else if (METRIC_TYPES[metric] === 'number') {
                                self.setMetricData(metric, C.Util.numberArrayToString(respData));
                            } else {
                                self.setMetricData(metric, respData);
                            }
                        }
                    }
                    metric = null;
                }
            });
        },

        setMetricData: function (name, value) {
            var metricsData = this.get('metricsData');
            //todo remove it when services will be fixed
            //never zero
            if (value == 0) {
                value = Math.floor((Math.random() * 30) + 1);
            }
            metricsData.set(name, value);
        }
    });

    Model.reopenClass({
        type: 'Spark',
        kind: 'Model',
        find: function (model_id, http) {

            model_id = model_id.split(':');

            var self = this,
                promise = Ember.Deferred.create(),
                app_id = model_id[0],
                spark_id = model_id[1];

            http.rest('apps', app_id, 'spark', spark_id, function (model, error) {

                model = self.transformModel(model);

                model.app = app_id;
                model = C.Spark.create(model);
                model.id = spark_id;
                model.name = spark_id;

                http.rest('apps', app_id, 'spark', spark_id, 'status', function (response) {
                    if (!$.isEmptyObject(response)) {
                        model.set('currentState', response.status);
                        promise.resolve(model);
                    } else {
                        promise.reject('Status not found');
                    }
                });

            });

            return promise;
        },

        transformModel: function (model) {

            var newModel = {};
            for (var i = EXPECTED_FIELDS.length - 1; i >= 0; i--) {
                newModel[EXPECTED_FIELDS[i]] = model[EXPECTED_FIELDS[i]];
            }
            if ('appId' in model || 'applicationId' in model) {
                newModel.appId = model.appId || model.applicationId;
            }
            return newModel;

        }
    });

    return Model;

});<|endoftext|>


<commit_before>import runValidation from '../utils/runValidation'

export default function validateFieldFactory (pathTemplate) {
  function validateField (context) {
    const path = typeof pathTemplate === 'function' ? pathTemplate(context).value : pathTemplate
    const fieldPath = path.split('.')
    const formPath = fieldPath.slice().splice(0, fieldPath.length - 1)
    const field = context.state.get(fieldPath)
    const form = context.state.get(formPath)
    const validationResult = runValidation(field, form)

    context.state.merge(fieldPath, validationResult)

    let dependentFields = []
    if (Array.isArray(field.dependsOn)) {
      dependentFields = field.dependsOn
    } else if (field.dependsOn) {
      dependentFields = [field.dependsOn]
    }

    const dependentOfValidationResult = dependentFields.reduce((currentValidationResult, stringPath) => {
      const dependentFieldPath = stringPath.split('.')
      const dependentFormPath = dependentFieldPath.slice().splice(0, dependentFieldPath.length - 1)
      const dependentField = context.state.get(dependentFieldPath)
      const dependentForm = context.state.get(dependentFormPath)
      if (!dependentForm || !dependentField) {
        throw new Error(`The path ${stringPath} used with "dependsOn" on field ${fieldPath.join('.')} is not correct, please check it`)
      }

      const dependentValidationResult = runValidation(dependentField, dependentForm)
      context.state.merge(dependentFieldPath, dependentValidationResult)

      if (currentValidationResult.isValid && !dependentValidationResult.isValid) {
        return Object.assign(currentValidationResult, { isValid: false })
      }

      return currentValidationResult
    }, validationResult)

    context.state.merge(fieldPath, dependentOfValidationResult)
  }

  return validateField
}
<commit_msg>refactor(forms): remove unnecessary merge from validateField (#531)<commit_after>import runValidation from '../utils/runValidation'

export default function validateFieldFactory (pathTemplate) {
  function validateField (context) {
    const path = typeof pathTemplate === 'function' ? pathTemplate(context).value : pathTemplate
    const fieldPath = path.split('.')
    const formPath = fieldPath.slice().splice(0, fieldPath.length - 1)
    const field = context.state.get(fieldPath)
    const form = context.state.get(formPath)
    const validationResult = runValidation(field, form)

    let dependentFields = []
    if (Array.isArray(field.dependsOn)) {
      dependentFields = field.dependsOn
    } else if (field.dependsOn) {
      dependentFields = [field.dependsOn]
    }

    const dependentOfValidationResult = dependentFields.reduce((currentValidationResult, stringPath) => {
      const dependentFieldPath = stringPath.split('.')
      const dependentFormPath = dependentFieldPath.slice().splice(0, dependentFieldPath.length - 1)
      const dependentField = context.state.get(dependentFieldPath)
      const dependentForm = context.state.get(dependentFormPath)
      if (!dependentForm || !dependentField) {
        throw new Error(`The path ${stringPath} used with "dependsOn" on field ${fieldPath.join('.')} is not correct, please check it`)
      }

      const dependentValidationResult = runValidation(dependentField, dependentForm)
      context.state.merge(dependentFieldPath, dependentValidationResult)

      if (currentValidationResult.isValid && !dependentValidationResult.isValid) {
        return Object.assign(currentValidationResult, { isValid: false })
      }

      return currentValidationResult
    }, validationResult)

    context.state.merge(fieldPath, dependentOfValidationResult)
  }

  return validateField
}
<|endoftext|>


<commit_before>// gulp/tasks/base/clean.js
'use strict';

// ----------------------------------
// available tasks:
//    'gulp clean'       : clean dest folder & caches
//    'gulp clean:cache' : clear all caches enough
// ----------------------------------
// plugins:
//     del        : $.del
//     gulp-cached: $.cached
// ----------------------------------
// config:
//     config.task.clean : task name
// ----------------------------------

module.exports = function(gulp, $, path, config) {

    // clear all caches enough
    gulp.task(config.task.clean + ':cache', function() {

        $.cached.caches = {};

    });

    // delete dest folder and clear all caches
    gulp.task(config.task.clean, [config.task.clean + ':cache'], function() {

        return $.del([
            path.to.dist.main
        ]);

    });

};<commit_msg>update clean task to delete prod folder<commit_after>// gulp/tasks/base/clean.js
'use strict';

// ----------------------------------
// available tasks:
//    'gulp clean'       : clean dest folder & caches
//    'gulp clean:cache' : clear all caches enough
// ----------------------------------
// plugins:
//     del        : $.del
//     gulp-cached: $.cached
// ----------------------------------
// config:
//     config.task.clean : task name
// ----------------------------------

module.exports = function(gulp, $, path, config) {

    // clear all caches enough
    gulp.task(config.task.clean + ':cache', function() {

        $.cached.caches = {};

    });

    // delete production folder [build/prod]
    gulp.task(config.task.clean + ':prod', function() {

        return $.del([
            path.to.dist.prod
        ]);

    });

    // delete dest folder [build] and clear all caches
    gulp.task(config.task.clean, [config.task.clean + ':cache'], function() {

        return $.del([
            path.to.dist.main
        ]);

    });

};<|endoftext|>