<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief tests for readonly mode of arango
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Esteban Lombeyda
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var jsunity = require("jsunity");
var arangodb = require("org/arangodb");

// -----------------------------------------------------------------------------
// --SECTION--                                                        test suite
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function dropDatabaseTestSuite () {
  var db;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      db._changeMode("Normal");
      db._createDatabase("testDB");
      db._changeMode("ReadOnly");
    },
    tearDown : function () {
      try {
        db._changeMode("Normal");
        db._dropDatabase("testDB");
        } catch (e) {
        }
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: creation of a data base in read only modes should faill
    ////////////////////////////////////////////////////////////////////////////////

    testCreateDatabase: function () {
      var not_modified = false;
      try {
        db._createDatabase("xxxDB");
        } catch (e) {
          not_modified = true;
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
      assertTrue(not_modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: droping of a data base in read only mode should be posible
      ////////////////////////////////////////////////////////////////////////////////

      testDropDatabase: function () {
        var modified = false;
        try {
          db._dropDatabase("testDB");
          modified = true;
        } catch (e) {
          not_modified = false;
        }
        assertTrue(modified);
     },
  };
}
////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function readOnlyDatabaseSuite () {
  var db;
  var collection;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      collection = db._createDocumentCollection("testCol");
      collection.save({_key: "testDocKey", a: 2 });
      db._changeMode("ReadOnly");
    },
    tearDown : function () {
      try {
        db._changeMode("Normal");
        collection.drop("testCol");
      } catch (e) {
        print(e);
      }
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (prefix)
    ////////////////////////////////////////////////////////////////////////////////

    testCreateDocumentCollection: function () {
      var not_modified = false;
      try {
        db._createDocumentCollection("abcDC");
        } catch (e) {
          not_modified = true;
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
      assertTrue(not_modified);
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (parameter)
    ////////////////////////////////////////////////////////////////////////////////

    testDropCollection: function () {
      var not_modified = false;
      try {
        db._createDocumentCollection("xxxDC");
        not_modified = true;
        } catch (e) {
      }
      assertFalse(not_modified);
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (optional)
    ////////////////////////////////////////////////////////////////////////////////

    testInsertDocument: function () {
      var modified = false;
      try {
        collection.save({a:1, b:2});
        modified = true;
        } catch (e) {
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: simple routing (optional)
      ////////////////////////////////////////////////////////////////////////////////

      testUpdateDocument: function () {
        var modified = false;
        try {
          collection.update("testDocKey", {name: "testing", a: 3});
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: simple routing (prefix vs non-prefix)
      ////////////////////////////////////////////////////////////////////////////////

      testRemoveDocument: function () {
        var modified = false;
        try {
          var removed = collection.remove("testDocKey");
          assertFalse(removed);
          modified = true;
        } catch (e) {
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: content string
      ////////////////////////////////////////////////////////////////////////////////

      testCreateBitArrayIndex: function () {
        var modified = false;
        try {
          collection.ensureBitarray("a", [1,2,3,4]);
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      testCreateHashIndex: function () {
        var modified = false;
        try {
          collection.ensureIndex({ type: "hash", fields: [ "name" ], unique: true });
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      testCreateGeoIndex: function () {
        var modified = false;
        try {
          collection.ensureIndex({ type: "geo1", fields: [ "x" ], unique: true });
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
       },

       testCreateGeo2Index: function () {
         var modified = false;
         try {
           collection.ensureIndex({ type: "geo2", fields: [ "x", "y" ], unique: true });
           modified = true;
         } catch (e) {
           assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
         }
         assertFalse(modified);
       },

       testCreateSkipListIndex: function () {
         var modified = false;
         try {
           collection.ensureIndex({ type: "skiplist", fields: [ "x" ]});
           modified = true;
         } catch (e) {
           assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
         }
         assertFalse(modified);
       },

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(dropDatabaseTestSuite);
jsunity.run(readOnlyDatabaseSuite);

return jsunity.done();

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @\\}\\)"
// End:
<commit_msg>Bug fix in setUp function<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief tests for readonly mode of arango
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Esteban Lombeyda
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var jsunity = require("jsunity");
var arangodb = require("org/arangodb");

// -----------------------------------------------------------------------------
// --SECTION--                                                        test suite
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function dropDatabaseTestSuite () {
  var db;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      db._changeMode("Normal");
      db._createDatabase("testDB");
      db._changeMode("ReadOnly");
    },
    tearDown : function () {
      try {
        db._changeMode("Normal");
        db._dropDatabase("testDB");
        } catch (e) {
        }
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: creation of a data base in read only modes should faill
    ////////////////////////////////////////////////////////////////////////////////

    testCreateDatabase: function () {
      var not_modified = false;
      try {
        db._createDatabase("xxxDB");
        } catch (e) {
          not_modified = true;
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
      assertTrue(not_modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: droping of a data base in read only mode should be posible
      ////////////////////////////////////////////////////////////////////////////////

      testDropDatabase: function () {
        var modified = false;
        try {
          db._dropDatabase("testDB");
          modified = true;
        } catch (e) {
          not_modified = false;
        }
        assertTrue(modified);
     },
  };
}
////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function readOnlyDatabaseSuite () {
  var db;
  var collection;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      db._drop("testCol");
      collection = db._createDocumentCollection("testCol");
      collection.save({_key: "testDocKey", a: 2 });
      db._changeMode("ReadOnly");
    },
    tearDown : function () {
      try {
        db._changeMode("Normal");
        collection.drop();
      } catch (e) {
      }
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (prefix)
    ////////////////////////////////////////////////////////////////////////////////

    testCreateDocumentCollection: function () {
      var not_modified = false;
      try {
        db._createDocumentCollection("abcDC");
        } catch (e) {
          not_modified = true;
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
      assertTrue(not_modified);
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (parameter)
    ////////////////////////////////////////////////////////////////////////////////

    testDropCollection: function () {
      var not_modified = false;
      try {
        db._createDocumentCollection("xxxDC");
        not_modified = true;
        } catch (e) {
      }
      assertFalse(not_modified);
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (optional)
    ////////////////////////////////////////////////////////////////////////////////

    testInsertDocument: function () {
      var modified = false;
      try {
        collection.save({a:1, b:2});
        modified = true;
        } catch (e) {
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: simple routing (optional)
      ////////////////////////////////////////////////////////////////////////////////

      testUpdateDocument: function () {
        var modified = false;
        try {
          collection.update("testDocKey", {name: "testing", a: 3});
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: simple routing (prefix vs non-prefix)
      ////////////////////////////////////////////////////////////////////////////////

      testRemoveDocument: function () {
        var modified = false;
        try {
          var removed = collection.remove("testDocKey");
          assertFalse(removed);
          modified = true;
        } catch (e) {
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: content string
      ////////////////////////////////////////////////////////////////////////////////

      testCreateBitArrayIndex: function () {
        var modified = false;
        try {
          collection.ensureBitarray("a", [1,2,3,4]);
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      testCreateHashIndex: function () {
        var modified = false;
        try {
          collection.ensureIndex({ type: "hash", fields: [ "name" ], unique: true });
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      testCreateGeoIndex: function () {
        var modified = false;
        try {
          collection.ensureIndex({ type: "geo1", fields: [ "x" ], unique: true });
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
       },

       testCreateGeo2Index: function () {
         var modified = false;
         try {
           collection.ensureIndex({ type: "geo2", fields: [ "x", "y" ], unique: true });
           modified = true;
         } catch (e) {
           assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
         }
         assertFalse(modified);
       },

       testCreateSkipListIndex: function () {
         var modified = false;
         try {
           collection.ensureIndex({ type: "skiplist", fields: [ "x" ]});
           modified = true;
         } catch (e) {
           assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
         }
         assertFalse(modified);
       },

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(dropDatabaseTestSuite);
jsunity.run(readOnlyDatabaseSuite);

return jsunity.done();

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @\\}\\)"
// End:
<|endoftext|>


<commit_before>import React from 'react';
import Sidebar from './left-container/sidebar';

const Adventures = props => {
  const {children, params} = props,
        {adventure} = params;

  return (

          <Sidebar adventure={adventure}/>

          <div className={`content`}>
            {children}

  );
};

export default Adventures;<commit_msg>Added proptypes to Adventures<commit_after>import React from 'react';
import Sidebar from './left-container/sidebar';

const Adventures = props => {
  const {children, params} = props,
        {adventure} = params;

  return (

          <Sidebar adventure={adventure}/>

          <div className={`content`}>
            {children}

  );
};

Adventures.propTypes = {
  children:  React.PropTypes.element,
  params:    React.PropTypes.object.isRequired,
  adventure: React.PropTypes.string
};

export default Adventures;<|endoftext|>


<commit_before>var vhome = document.getElementById("ihome");
var vabout = document.getElementById("iabout");
var vchildhood = document.getElementById("ichildhood");
var vcollege = document.getElementById("icollege");
var vnss = document.getElementById("inss");
var vlove = document.getElementById("ilove");
var vstep = document.getElementById("istep");
var vdad = document.getElementById("idad");
var vcontact = document.getElementById("icontact");
var vfeedback = document.getElementById("ifeedback");

var ta = document.getElementById('contentdiv');
var x = new XMLHttpRequest;
function funct(){
	ta.innerHTML = x.responseText;
}

function func(){
	x.open("GET", "pages/home.html");
	x.onreadystatechange =funct;
	x.send();
}

function fhome(){
	x.abort();
	x.open("GET", "pages/home.html");
	x.onreadystatechange =funct;
	x.send();
}

function fabout(){
	x.abort();
	x.open("GET", "pages/about.html");
	x.onreadystatechange =funct;
	x.send();
}

function fchildhood(){
	x.abort();
	x.open("GET", "pages/childhood.html");
	x.onreadystatechange =funct;
	x.send();
}

function fcollege(){
	x.abort();
	x.open("GET", "pages/college.html");
	x.onreadystatechange =funct;
	x.send();
}

function fnss(){
	x.abort();
	x.open("GET", "pages/nss.html");
	x.onreadystatechange =funct;
	x.send();
}

function flove(){
	x.abort();
	x.open("GET", "pages/love.html");
	x.onreadystatechange =funct;
	x.send();
}

function fstep(){
	x.abort();
	x.open("GET", "pages/step.html");
	x.onreadystatechange =funct;
	x.send();
}

function fdad(){
	x.abort();
	x.open("GET", "pages/dad.html");
	x.onreadystatechange =funct;
	x.send();
}

function fcontact(){
	x.abort();
	x.open("GET", "pages/contact.html");
	x.onreadystatechange =funct;
	x.send();
}

function ffeedback(){
	x.abort();
	x.open("GET", "pages/feedback.html");
	x.onreadystatechange =funct;
	x.send();
}

window.onload=func;

if(vhome){
if(vhome.addEventListener)
	vhome.addEventListener("click", fhome, false);
else if(vhome.attachEvent)
	vhome.attachEvent('onclick', fhome);
}

if(vabout.addEventListener)
	vabout.addEventListener("click", fabout, false);
else if(vabout.attachEvent)
	vabout.attachEvent('onclick', fabout);

if(vchildhood.addEventListener)
	vchildhood.addEventListener("click", fchildhood, false);
else if(vchildhood.attachEvent)
	vchildhood.attachEvent('onclick', fchildhood);

if(vcollege.addEventListener)
	vcollege.addEventListener("click", fcollege, false);
else if(vcollege.attachEvent)
	vcollege.attachEvent('onclick', fcollege);

if(vnss.addEventListener)
	vnss.addEventListener("click", fnss, false);
else if(vnss.attachEvent)
	vnss.attachEvent('onclick', fnss);

if(vlove.addEventListener)
	vlove.addEventListener("click", flove, false);
else if(vlove.attachEvent)
	vlove.attachEvent('onclick', flove);

if(vstep.addEventListener)
	vstep.addEventListener("click", fstep, false);
else if(vstep.attachEvent)
	vstep.attachEvent('onclick', fstep);

if(vdad.addEventListener)
	vdad.addEventListener("click", fdad, false);
else if(vdad.attachEvent)
	vdad.attachEvent('onclick', fdad);

if(vcontact.addEventListener)
	vcontact.addEventListener("click", fcontact, false);
else if(vcontact.attachEvent)
	vcontact.attachEvent('onclick', fcontact);

if(vfeedback.addEventListener)
	vfeedback.addEventListener("click", ffeedback, false);
else if(vfeedback.attachEvent)
	vfeedback.attachEvent('onclick', ffeedback);
<commit_msg>Update ajaxed.js<commit_after>var vhome = document.getElementById("ihome");
var vabout = document.getElementById("iabout");
var vchildhood = document.getElementById("ichildhood");
var vcollege = document.getElementById("icollege");
var vnss = document.getElementById("inss");
var vlove = document.getElementById("ilove");
var vstep = document.getElementById("istep");
var vdad = document.getElementById("idad");
var vcontact = document.getElementById("icontact");
var vfeedback = document.getElementById("ifeedback");

var ta = document.getElementById('contentdiv');
var x = new XMLHttpRequest;
function funct(){
	ta.innerHTML = x.responseText;
}

function func(){
	x.open("GET", "pages/home.html");
	x.onreadystatechange =funct;
	x.send();
}

function fhome(){
	x.abort();
	x.open("GET", "pages/home.html");
	x.onreadystatechange =funct;
	x.send();
}

function fabout(){
	x.abort();
	x.open("GET", "pages/about.html");
	x.onreadystatechange =funct;
	x.send();
}

function fchildhood(){
	x.abort();
	x.open("GET", "pages/childhood.html");
	x.onreadystatechange =funct;
	x.send();
}

function fcollege(){
	x.abort();
	x.open("GET", "pages/college.html");
	x.onreadystatechange =funct;
	x.send();
}

function fnss(){
	x.abort();
	x.open("GET", "pages/nss.html");
	x.onreadystatechange =funct;
	x.send();
}

function flove(){
	x.abort();
	x.open("GET", "pages/love.html");
	x.onreadystatechange =funct;
	x.send();
}

function fstep(){
	x.abort();
	x.open("GET", "pages/step.html");
	x.onreadystatechange =funct;
	x.send();
}

function fdad(){
	x.abort();
	x.open("GET", "pages/dad.html");
	x.onreadystatechange =funct;
	x.send();
}

function fcontact(){
	x.abort();
	x.open("GET", "pages/contact.html");
	x.onreadystatechange =funct;
	x.send();
}

function ffeedback(){
	x.abort();
	x.open("GET", "pages/feedback.html");
	x.onreadystatechange =funct;
	x.send();
}

window.onload=func;

if(vhome){
	if(vhome.addEventListener)
		vhome.addEventListener("click", fhome, false);
	else if(vhome.attachEvent)
		vhome.attachEvent('onclick', fhome);
}

if(vabout){
	if(vabout.addEventListener)
		vabout.addEventListener("click", fabout, false);
	else if(vabout.attachEvent)
		vabout.attachEvent('onclick', fabout);
}

if(vchildhood){
	if(vchildhood.addEventListener)
		vchildhood.addEventListener("click", fchildhood, false);
	else if(vchildhood.attachEvent)
		vchildhood.attachEvent('onclick', fchildhood);
}

if(vcollege){
	if(vcollege.addEventListener)
		vcollege.addEventListener("click", fcollege, false);
	else if(vcollege.attachEvent)
		vcollege.attachEvent('onclick', fcollege);
}

if(vnss){
	if(vnss.addEventListener)
		vnss.addEventListener("click", fnss, false);
	else if(vnss.attachEvent)
		vnss.attachEvent('onclick', fnss);
}

if(vlove){
	if(vlove.addEventListener)
		vlove.addEventListener("click", flove, false);
	else if(vlove.attachEvent)
		vlove.attachEvent('onclick', flove);
}

if(vstep){
	if(vstep.addEventListener)
		vstep.addEventListener("click", fstep, false);
	else if(vstep.attachEvent)
		vstep.attachEvent('onclick', fstep);
}

if(vdad){
	if(vdad.addEventListener)
		vdad.addEventListener("click", fdad, false);
	else if(vdad.attachEvent)
		vdad.attachEvent('onclick', fdad);
}

if(vcontact){
	if(vcontact.addEventListener)
		vcontact.addEventListener("click", fcontact, false);
	else if(vcontact.attachEvent)
		vcontact.attachEvent('onclick', fcontact);
}

if(vfeedback){
	if(vfeedback.addEventListener)
		vfeedback.addEventListener("click", ffeedback, false);
	else if(vfeedback.attachEvent)
		vfeedback.attachEvent('onclick', ffeedback);
}
<|endoftext|>


<commit_before>var root_url = 'http://54.215.155.53:8080';

$.getJSON( root_url + "/data/getvalues", function( data ) {

    function compare(a, b) {
        a = a.toString().toLowerCase();
        b = b.toString().toLowerCase();
        if( a  b )
            return 1;
        return 0;
    }

    var tests = data['test'].sort( compare );
    var revs = data['rev'];
    var platforms = data['platform'].sort( compare );
    if (parseInt(results['showAll']) == 1) {
        document.getElementById("checkbox").checked = true;
    }

    for(var i in tests) {
        var newoption = document.createElement("option");
         newoption.id = "test";
         var value = tests[i][0];
            $("#test").append("<option value=\""+value+"\">"+value+"</option>");
     }

    for(i in revs) {
        var newoption = document.createElement("option");
         newoption.id = "rev";
         var value = revs[i][0];
            $("#rev").append("<option value=\""+value+"\">"+value+"</option>");
    }

    for(i in platforms) {
        var newoption = document.createElement("option");
         newoption.id = "platform";
         var value = platforms[i][0];
            $("#platform").append("<option value=\""+value+"\">"+value+"</option>");
    }

    document.getElementById("rev").value = results['rev'];
    document.getElementById("test").selectedIndex = results['testIndex'];
    document.getElementById("platform").selectedIndex = results['platIndex'];

});

$(document).ready(function() {

                    $('#button').click(function() {
                            var rev = $('#rev').val();
                            var test = $('#test').val();
                            var platform = $('#platform').val();
                            var showall = 0;
                            var testIndex = $("select[id='test'] option:selected").index();
                            var platIndex = $("select[id='platform'] option:selected").index();
                            if($('#checkbox').is(":checked")) {
                                console.log("checked");
                                showall = 1;
                            }
                         document.cookie="platform = "+platform;
                         document.cookie="test = "+test;
                         location.href = "?rev="+rev+"&showAll="+showall+"&testIndex="+testIndex+"&platIndex="+platIndex;

                    });
});

function hideMerged(originalkeyrev, showall) {
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);

        var fields = ["date", "branch", "test", "platform", "percent", "graphurl", "changeset", "tbplurl", "comment", "bug", "status"]
        var alerts = raw_data.alerts;

        var keyrev = "";
        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["mergedfrom"] == originalkeyrev) {
                tbl = document.getElementById(originalkeyrev + "-tbl");
            } else {
                continue;
            }
            var row = $("#" + alerts[alert]["id"] + "-" + originalkeyrev);
            if (row) {
                row.remove();
            }
        }
        var mergedfromhtml = "view merged alerts";

          $("#" + originalkeyrev + "-hdr").html("
" + originalkeyrev + "
" + mergedfromhtml);
    }
    req.open('get', root_url + '/data/mergedalerts?keyrev=' + originalkeyrev, true);
    req.send();
}

function showMerged(originalkeyrev, showall) {
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);
        var alerts = raw_data.alerts;

        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["mergedfrom"] != originalkeyrev) {
                continue;
            }
            tbl = document.getElementById(originalkeyrev + "-tbl");
            addAlertToUI(tbl, alerts[alert], showall, originalkeyrev);
        }
        var mergedfromhtml = "hide merged alerts";

          $("#" + originalkeyrev + "-hdr").html("
" + originalkeyrev + "
" + mergedfromhtml);
    }
    req.open('get', root_url + '/data/mergedalerts?keyrev=' + originalkeyrev, true);
    req.send();
}

function addMergedLinks(showall) {
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);

        var fields = ["id", "date", "bug", "status", "keyrevision", "bugcount", "mergedfrom"]
        var alerts = raw_data.alerts;

        var count = 0;
        for (var alert in alerts) {
            if (alerts[alert]['mergedfrom'] != '') {
                var mf = alerts[alert]['mergedfrom'];
                if ($("#" + mf + "-hdr").html() == "") {
                    continue;
                }

                var mergedfromhtml = "view merged alerts";

                  $("#" + mf + "-hdr").html("
" + mf + "
" + mergedfromhtml);
            }
        }
    }
    req.open('get', root_url + '/data/mergedids', true);
    req.send();
}

function updateStatus(alertid, duplicate, bugid, mergedfrom) {
    var status = $("#" + alertid + "-status").val();
    if (status == 'Duplicate') {
        // popup window with field for duplicate, seeded with alert['duplicate']
        // consider merged rev if needed
        suggestedDuplicate = duplicate;
        if (suggestedDuplicate == 'null' || suggestedDuplicate == '') {
            suggestedDuplicate = mergedfrom;
        }

        AddDuplicateUI.openDuplicateBox(alertid, suggestedDuplicate);
    } else if (status == 'Backout') {
        var bug = bugid;
        if (bug == '') {
            bug = $("#" + alertid + "-bug").val();
        }
        AddBugUI.openBugBox(alertid, bug, 'Backout');
    } else {
        $.ajax({
          url: "data/updatestatus",
          type: "POST",
          data: {
            id: alertid,
            status: status,
          }
        });
    }
}

function updateBug(alertid, bugid, status) {
    var bug = bugid;
    if (bug == '') {
        bug = $("#" + alertid + "-bug").val();
    }
    if (status == '') {
        status = 'NEW';
    }

    AddBugUI.openBugBox(alertid, bug, status);
}

function updateTbplURL(alertid, tbplurl) {
    AddTbplUI.openTbplBox(alertid, tbplurl);
}

function addAlertToUI(tbl,alert,showall){
    addMergedAlertToUI(tbl, alert, showall, "");
}

// Function idDescending sorts the objects in the descending order of their id. This way, we can view the most recent alerts at the top.
// The objects have been sorted based on their id and not on their date as sorting by the date field was not working.
function idDescending(a, b) {
    if (a["id"] < b["id"]) {
        return 1;
    }
    else {
        return -1;
    }
}

function loadAllAlerts(showall, rev, test, platform) {
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);
        var alerts = raw_data.alerts;
        alerts.sort(idDescending);

        var keyrev = "";
        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["keyrevision"] != keyrev) {
                keyrev = alerts[alert]["keyrevision"];
                if ($("#" + keyrev + "-hdr").html() == null) {
                    var newdiv = document.createElement("div");
                    newdiv.id = keyrev;
                    $("#revisions").append(newdiv);

                    $("#" + keyrev).append("
" + keyrev + "
");

                }
                if ($("#" + keyrev + "-tbl").html() == null) {
                    var kdiv = document.getElementById(keyrev);
                    var newtbl = document.createElement("table");
                    newtbl.id = keyrev + '-tbl';
                    $("#" + keyrev).append(newtbl);
                }

                 $("#" + keyrev + "-hdr").html("
" + keyrev + "
");
                tbl = document.getElementById(keyrev + "-tbl");
            }
            var r = addAlertToUI(tbl, alerts[alert], showall);
            if ($("#" + keyrev + '-tbl tr').size() == 0) {
                $("#" + keyrev + "-hdr").html("");
            }
        }
        addMergedLinks(showall);
        AddCommentUI.init();
        AddDuplicateUI.init();
        AddBugUI.init();
        AddTbplUI.init();
    }
    req.open('get', (root_url + '/data/alertsbyrev?rev='+rev+'&test='+test+'&platform='+platform), true);
    req.send();
}

function editAlert(id, body) {
    return function() {
      AddCommentUI.openCommentBox(id, body);
    }
}

function hideDiv(name) {
    document.getElementById(name).style.display = "none";
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

function getJsonFromUrl() {
  var query = location.search.substr(1);
  var data = query.split("&");
  var result = {};
  for(var i=0; i<data.length; i++) {
    var item = data[i].split("=");
    result[item[0]] = item[1];
  }
  return result;
}<commit_msg>Bug 1033635 - [ui] in Alert Manager sort the fields for platform and test in the top nav bar alphabetically<commit_after>var root_url = 'http://54.215.155.53:8080';

$.getJSON( root_url + "/data/getvalues", function( data ) {

    function compare(a, b) {
        a = a.toString().toLowerCase();
        b = b.toString().toLowerCase();
        if( a  b )
            return 1;
        return 0;
    }

    var tests = data['test'].sort( compare );
    var revs = data['rev'];
    var platforms = data['platform'].sort( compare );
    if (parseInt(results['showAll']) == 1) {
        document.getElementById("checkbox").checked = true;
    }

    for(var i in tests) {
        var newoption = document.createElement("option");
         newoption.id = "test";
         var value = tests[i][0];
            $("#test").append("<option value=\""+value+"\">"+value+"</option>");
     }

    for(i in revs) {
        var newoption = document.createElement("option");
         newoption.id = "rev";
         var value = revs[i][0];
            $("#rev").append("<option value=\""+value+"\">"+value+"</option>");
    }

    for(i in platforms) {
        var newoption = document.createElement("option");
         newoption.id = "platform";
         var value = platforms[i][0];
            $("#platform").append("<option value=\""+value+"\">"+value+"</option>");
    }

    document.getElementById("rev").value = results['rev'];
    document.getElementById("test").selectedIndex = results['testIndex'];
    document.getElementById("platform").selectedIndex = results['platIndex'];

});

$(document).ready(function() {

                    $('#button').click(function() {
                            var rev = $('#rev').val();
                            var test = $('#test').val();
                            var platform = $('#platform').val();
                            var showall = 0;
                            var testIndex = $("select[id='test'] option:selected").index();
                            var platIndex = $("select[id='platform'] option:selected").index();
                            if($('#checkbox').is(":checked")) {
                                console.log("checked");
                                showall = 1;
                            }
                         document.cookie="platform = "+platform;
                         document.cookie="test = "+test;
                         location.href = "?rev="+rev+"&showAll="+showall+"&testIndex="+testIndex+"&platIndex="+platIndex;

                    });
});

function hideMerged(originalkeyrev, showall) {
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);

        var fields = ["date", "branch", "test", "platform", "percent", "graphurl", "changeset", "tbplurl", "comment", "bug", "status"]
        var alerts = raw_data.alerts;

        var keyrev = "";
        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["mergedfrom"] == originalkeyrev) {
                tbl = document.getElementById(originalkeyrev + "-tbl");
            } else {
                continue;
            }
            var row = $("#" + alerts[alert]["id"] + "-" + originalkeyrev);
            if (row) {
                row.remove();
            }
        }
        var mergedfromhtml = "view merged alerts";

          $("#" + originalkeyrev + "-hdr").html("
" + originalkeyrev + "
" + mergedfromhtml);
    }
    req.open('get', root_url + '/data/mergedalerts?keyrev=' + originalkeyrev, true);
    req.send();
}

function showMerged(originalkeyrev, showall) {
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);
        var alerts = raw_data.alerts;

        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["mergedfrom"] != originalkeyrev) {
                continue;
            }
            tbl = document.getElementById(originalkeyrev + "-tbl");
            addAlertToUI(tbl, alerts[alert], showall, originalkeyrev);
        }
        var mergedfromhtml = "hide merged alerts";

          $("#" + originalkeyrev + "-hdr").html("
" + originalkeyrev + "
" + mergedfromhtml);
    }
    req.open('get', root_url + '/data/mergedalerts?keyrev=' + originalkeyrev, true);
    req.send();
}

function addMergedLinks(showall) {
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);

        var fields = ["id", "date", "bug", "status", "keyrevision", "bugcount", "mergedfrom"]
        var alerts = raw_data.alerts;

        var count = 0;
        for (var alert in alerts) {
            if (alerts[alert]['mergedfrom'] != '') {
                var mf = alerts[alert]['mergedfrom'];
                if ($("#" + mf + "-hdr").html() == "") {
                    continue;
                }

                var mergedfromhtml = "view merged alerts";

                  $("#" + mf + "-hdr").html("
" + mf + "
" + mergedfromhtml);
            }
        }
    }
    req.open('get', root_url + '/data/mergedids', true);
    req.send();
}

function updateStatus(alertid, duplicate, bugid, mergedfrom) {
    var status = $("#" + alertid + "-status").val();
    if (status == 'Duplicate') {
        // popup window with field for duplicate, seeded with alert['duplicate']
        // consider merged rev if needed
        suggestedDuplicate = duplicate;
        if (suggestedDuplicate == 'null' || suggestedDuplicate == '') {
            suggestedDuplicate = mergedfrom;
        }

        AddDuplicateUI.openDuplicateBox(alertid, suggestedDuplicate);
    } else if (status == 'Backout') {
        var bug = bugid;
        if (bug == '') {
            bug = $("#" + alertid + "-bug").val();
        }
        AddBugUI.openBugBox(alertid, bug, 'Backout');
    } else {
        $.ajax({
          url: "data/updatestatus",
          type: "POST",
          data: {
            id: alertid,
            status: status,
          }
        });
    }
}

function updateBug(alertid, bugid, status) {
    var bug = bugid;
    if (bug == '') {
        bug = $("#" + alertid + "-bug").val();
    }
    if (status == '') {
        status = 'NEW';
    }

    AddBugUI.openBugBox(alertid, bug, status);
}

function updateTbplURL(alertid, tbplurl) {
    AddTbplUI.openTbplBox(alertid, tbplurl);
}

function addAlertToUI(tbl,alert,showall){
    addMergedAlertToUI(tbl, alert, showall, "");
}

// Function idDescending sorts the objects in the descending order of their id. This way, we can view the most recent alerts at the top.
// The objects have been sorted based on their id and not on their date as sorting by the date field was not working.
function idDescending(a, b) {
    if (a["id"] < b["id"]) {
        return 1;
    }
    else {
        return -1;
    }
}

function loadAllAlerts(showall, rev, test, platform) {
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);
        var alerts = raw_data.alerts;
        alerts.sort(idDescending);

        var keyrev = "";
        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["keyrevision"] != keyrev) {
                keyrev = alerts[alert]["keyrevision"];
                if ($("#" + keyrev + "-hdr").html() == null) {
                    var newdiv = document.createElement("div");
                    newdiv.id = keyrev;
                    $("#revisions").append(newdiv);

                    $("#" + keyrev).append("
" + keyrev + "
");

                }
                if ($("#" + keyrev + "-tbl").html() == null) {
                    var kdiv = document.getElementById(keyrev);
                    var newtbl = document.createElement("table");
                    newtbl.id = keyrev + '-tbl';
                    $("#" + keyrev).append(newtbl);
                }

                 $("#" + keyrev + "-hdr").html("
" + keyrev + "
");
                tbl = document.getElementById(keyrev + "-tbl");
            }
            var r = addAlertToUI(tbl, alerts[alert], showall);
            if ($("#" + keyrev + '-tbl tr').size() == 0) {
                $("#" + keyrev + "-hdr").html("");
            }
        }
        addMergedLinks(showall);
        AddCommentUI.init();
        AddDuplicateUI.init();
        AddBugUI.init();
        AddTbplUI.init();
    }
    req.open('get', (root_url + '/data/alertsbyrev?rev='+rev+'&test='+test+'&platform='+platform), true);
    req.send();
}

function editAlert(id, body) {
    return function() {
      AddCommentUI.openCommentBox(id, body);
    }
}

function hideDiv(name) {
    document.getElementById(name).style.display = "none";
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

function getJsonFromUrl() {
  var query = location.search.substr(1);
  var data = query.split("&");
  var result = {};
  for(var i=0; i<data.length; i++) {
    var item = data[i].split("=");
    result[item[0]] = item[1];
  }
  return result;
}

<|endoftext|>


<commit_before>/**
 * Copyright 2013-2014, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @emails react-core
 */

"use strict";

var React;

describe('ReactTextComponent', function() {
  beforeEach(function() {
    React = require('React');
  });

  it('should escape the rootID', function(){
    var ThisThingShouldBeEscaped = '">>> LULZ <<<"';
    var ThisThingWasBeEscaped = '">>> LULZ <<<"';
    var thing =
LULZ
;
    var html = React.renderToString(thing);
    expect(html).not.toContain(ThisThingShouldBeEscaped);
    expect(html).toContain(ThisThingWasBeEscaped);
  })
});
<commit_msg>Test that text spans aren't remounted needlessly<commit_after>/**
 * Copyright 2013-2014, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @emails react-core
 */

"use strict";

var React;

describe('ReactTextComponent', function() {
  beforeEach(function() {
    React = require('React');
  });

  it('should escape the rootID', function() {
    var ThisThingShouldBeEscaped = '">>> LULZ <<<"';
    var ThisThingWasBeEscaped = '">>> LULZ <<<"';
    var thing =
LULZ
;
    var html = React.renderToString(thing);
    expect(html).not.toContain(ThisThingShouldBeEscaped);
    expect(html).toContain(ThisThingWasBeEscaped);
  });

  it('updates a mounted text component in place', function() {
    var el = document.createElement('div');
    var inst = React.render(
{'foo'}{'bar'}
, el);

    var foo = inst.getDOMNode().children[0];
    var bar = inst.getDOMNode().children[1];
    expect(foo.tagName).toBe('SPAN');
    expect(bar.tagName).toBe('SPAN');

    var inst = React.render(
{'baz'}{'qux'}
, el);
    // After the update, the spans should have stayed in place (as opposed to
    // getting unmounted and remounted)
    expect(inst.getDOMNode().children[0]).toBe(foo);
    expect(inst.getDOMNode().children[1]).toBe(bar);
  });
});
<|endoftext|>


<commit_before>const PLATFORMS = [
  'h5',
  'app-plus',
  'mp-weixin',
  'mp-qq',
  'mp-baidu',
  'mp-alipay',
  'mp-toutiao'
]

module.exports = {
  initCustomScript (name, pkgPath) {
    const pkg = require(pkgPath)
    const uniAppOptions = pkg['uni-app']

    let scriptOptions = false

    if (uniAppOptions && uniAppOptions['scripts']) {
      scriptOptions = uniAppOptions['scripts'][name]
    }

    if (!scriptOptions) {
      console.error(`package.json->uni-app->scripts->${name} 不存在`)
      process.exit(0)
    }

    if (!scriptOptions.env || !scriptOptions.env.UNI_PLATFORM) {
      console.error(`package.json->uni-app->scripts->${name}->env 不存在,必须配置 env->UNI_PLATFORM 基础平台`)
      process.exit(0)
    }

    if (PLATFORMS.indexOf(scriptOptions.env.UNI_PLATFORM) === -1) {
      console.error(`UNI_PLATFORM 支持一下平台 ${JSON.stringify(PLATFORMS)}`)
      process.exit(0)
    }

    process.env.UNI_PLATFORM = scriptOptions.env.UNI_PLATFORM

    process.UNI_SCRIPT_ENV = scriptOptions.env || {}
    process.UNI_SCRIPT_DEFINE = scriptOptions.define || {}

    return scriptOptions
  }
}
<commit_msg>fix: 修正错别字<commit_after>const PLATFORMS = [
  'h5',
  'app-plus',
  'mp-weixin',
  'mp-qq',
  'mp-baidu',
  'mp-alipay',
  'mp-toutiao'
]

module.exports = {
  initCustomScript (name, pkgPath) {
    const pkg = require(pkgPath)
    const uniAppOptions = pkg['uni-app']

    let scriptOptions = false

    if (uniAppOptions && uniAppOptions['scripts']) {
      scriptOptions = uniAppOptions['scripts'][name]
    }

    if (!scriptOptions) {
      console.error(`package.json->uni-app->scripts->${name} 不存在`)
      process.exit(0)
    }

    if (!scriptOptions.env || !scriptOptions.env.UNI_PLATFORM) {
      console.error(`package.json->uni-app->scripts->${name}->env 不存在,必须配置 env->UNI_PLATFORM 基础平台`)
      process.exit(0)
    }

    if (PLATFORMS.indexOf(scriptOptions.env.UNI_PLATFORM) === -1) {
      console.error(`UNI_PLATFORM 支持以下平台 ${JSON.stringify(PLATFORMS)}`)
      process.exit(0)
    }

    process.env.UNI_PLATFORM = scriptOptions.env.UNI_PLATFORM

    process.UNI_SCRIPT_ENV = scriptOptions.env || {}
    process.UNI_SCRIPT_DEFINE = scriptOptions.define || {}

    return scriptOptions
  }
}
<|endoftext|>


<commit_before>'use strict';

const fs = require("fs");
const async = require('async');

const utils = require("../../../utils/utils.js");

function checkIfError(soajs, mainCb, data, cb) {
	utils.checkErrorReturn(soajs, mainCb, data, cb);
}

let infraColname = 'infra';
const BL = {
	model: null,

	/**
	 * Get logs of a container
	 *
	 * @param {Object} config
	 * @param {Object} soajs
	 * @param {Object} deployer
	 * @param {Function} cbMain
	 */
	"streamLogs": function (config, soajs, deployer, cbMain) {
		if((!soajs.inputmaskData.technology || soajs.inputmaskData.technology=== '' ) && !soajs.inputmaskData.taskId){
			return cbMain({code : 173, msg: "Invalid or Missing taskId in parameters!"});
		}

		async.auto({
			"getEnvironment": (mCb) =>{
				utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), (error, envRecord) => {
					checkIfError(soajs, mCb, { config: config, error: error || !envRecord, code: 600 }, () => {
						return mCb(null, envRecord);
					});
				});

			},
			"getInfra": (mCb) =>{
				//if infra id provided, use it
				//else pull based on env code
				if (soajs.inputmaskData.infraId) {
					soajs.inputmaskData.id = soajs.inputmaskData.infraId;
					BL.model.validateId(soajs, (err) => {
						checkIfError(soajs, mCb, {config: config, error: err, code: 490}, () => {
							let opts = {
								collection: infraColname,
								conditions: {
									_id: soajs.inputmaskData.id
								}
							};
							BL.model.findEntry(soajs, opts, function (err, infraRecord) {
								checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
									checkIfError(soajs, mCb, {
										config: config,
										error: !infraRecord,
										code: 600
									}, () => {
										return mCb(null, infraRecord);
									});
								});
							});
						});
					});
				}
				else {
					let opts = {
						collection: infraColname,
						conditions: {
							"deployments.environments": {"$in": [soajs.inputmaskData.env.toUpperCase()]}
						}
					};
					BL.model.findEntry(soajs, opts, function (err, infraRecord) {
						checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
							checkIfError(soajs, mCb, {config: config, error: !infraRecord, code: 600}, () => {
								return mCb(null, infraRecord);
							});
						});
					});
				}
			},
			"callDeployer": ["getEnvironment", "getInfra", (info, mCb) =>{
				let options = utils.buildDeployerOptions(info.getEnvironment, soajs, BL);
				options.infra = info.getInfra;
				//need to supply the stack if infra has more than drivers
				options.infra.stack = utils.getDeploymentFromInfra(options.infra, info.getEnvironment.code)[0];

				let technology = soajs.inputmaskData.technology || options.strategy;
				options.params = {
					id: soajs.inputmaskData.serviceId,
					taskId: soajs.inputmaskData.taskId,
					follow: soajs.inputmaskData.follow,
					filter: soajs.inputmaskData.filter || ""
				};

				deployer.execute({type: "infra", name: info.getInfra.name, technology: technology}, 'getContainerLogs', options, mCb);
				// TODO: handle logs Streaming once UI supports it
				// if(soajs.inputmaskData.follow) {
				// 	logs.on('data', (data) => {
				// 		console.log('---------------------------');
				// 		console.log(data.toString());
				// 		console.log('---------------------------');
				// 	});
				// }
				// else {
				// 	return cbMain(null, logs);
				// }
			}]
		}, (error, results) => {
			checkIfError(soajs, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, function () {
				return cbMain(null, results.callDeployer);
			});
		});
	},

	/**
	 * Perform a maintenance operation on a deployed SOAJS service
	 *
	 * @param {Object} config
	 * @param {Object} soajs
	 * @param {Object} deployer
	 * @param {Function} cbMain
	 */
	"maintenance": function (config, soajs, deployer, cbMain) {
		async.auto({
			"checkIfServiceOrDaemon": (mCb) =>{
				if(['service','daemon'].indexOf(soajs.inputmaskData.type) === -1){
					return mCb();
				}

				let opts = {
					collection: (soajs.inputmaskData.type === 'service') ? 'services' : 'daemons',
					conditions: {
						name: soajs.inputmaskData.serviceName
					}
				};
				BL.model.findEntry(soajs, opts, mCb);
			},
			"getEnvironment": (mCb) =>{
				utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), (error, envRecord) => {
					checkIfError(soajs, mCb, { config: config, error: error || !envRecord, code: 600 }, () => {
						return mCb(null, envRecord);
					});
				});
			},
			"getInfra": (mCb) =>{
				//if infra id provided, use it
				//else pull based on env code
				if (soajs.inputmaskData.infraId) {
					soajs.inputmaskData.id = soajs.inputmaskData.infraId;
					BL.model.validateId(soajs, (err) => {
						checkIfError(soajs, mCb, {config: config, error: err, code: 490}, () => {
							let opts = {
								collection: infraColname,
								conditions: {
									_id: soajs.inputmaskData.id
								}
							};
							BL.model.findEntry(soajs, opts, function (err, infraRecord) {
								checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
									checkIfError(soajs, mCb, {
										config: config,
										error: !infraRecord,
										code: 600
									}, () => {
										return mCb(null, infraRecord);
									});
								});
							});
						});
					});
				}
				else {
					let opts = {
						collection: infraColname,
						conditions: {
							"deployments.environments": {"$in": [soajs.inputmaskData.env.toUpperCase()]}
						}
					};
					BL.model.findEntry(soajs, opts, function (err, infraRecord) {
						checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
							checkIfError(soajs, mCb, {config: config, error: !infraRecord, code: 600}, () => {
								return mCb(null, infraRecord);
							});
						});
					});
				}
			},
			"callDeployer": ["checkIfServiceOrDaemon", "getEnvironment", "getInfra", (info, mCb) =>{
				let options = utils.buildDeployerOptions(info.getEnvironment, soajs, BL);
				options.infra = info.getInfra;
				//need to supply the stack if infra has more than drivers
				options.infra.stack = utils.getDeploymentFromInfra(options.infra, info.getEnvironment.code)[0];
				let technology = soajs.inputmaskData.technology || options.strategy;
				options.params = {
					toEnv: soajs.inputmaskData.env,
					id: soajs.inputmaskData.serviceId,
					network: config.network,
					operation: soajs.inputmaskData.operation,
					serviceName: soajs.inputmaskData.serviceName
				};

				if(info.checkIfServiceOrDaemon && info.checkIfServiceOrDaemon.port){
					options.params.maintenancePort = info.checkIfServiceOrDaemon.port + info.getEnvironment.services.config.ports.maintenanceInc;
				}

				soajs.log.info(`Maintenance operation ${soajs.inputmaskData.operation} started!`);
				deployer.execute({ type: "infra", name: info.getInfra.name, technology: technology }, 'maintenance', options, mCb);
			}]
		}, (error, results) => {
			checkIfError(soajs, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, function () {
				return cbMain(null, results.callDeployer);
			});
		});
	},

	/**
	 * Perform a maintenance operation on a deployed SOAJS service
	 *
	 * @param {Object} config
	 * @param {Object} soajs
	 * @param {Object} deployer
	 * @param {Function} cbMain
	 */
	"maintenanceVM": function (config, soajs, deployer, cbMain) {
		async.auto({
			"getEnvironment": (mCb) =>{
				if (!soajs.inputmaskData.env){
					return mCb(null, true);
				}
				utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), (error, envRecord) => {
					checkIfError(soajs, mCb, { config: config, error: error || !envRecord, code: 600 }, mCb);
				});
			},
			"getInfra": (mCb) =>{
				//if infra id provided, use it
				//else pull based on env code
				soajs.inputmaskData.id = soajs.inputmaskData.infraId;
				BL.model.validateId(soajs, (err) => {
					checkIfError(soajs, mCb, {config: config, error: err, code: 490}, () => {
						let opts = {
							collection: infraColname,
							conditions: {
								_id: soajs.inputmaskData.id
							}
						};
						BL.model.findEntry(soajs, opts, function (err, infraRecord) {
							checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
								checkIfError(soajs, mCb, {
									config: config,
									error: !infraRecord,
									code: 600
								}, () => {
									return mCb(null, infraRecord);
								});
							});
						});
					});
				});
			},
		}, (error, result) => {
			checkIfError(soajs, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, ()=>{
				let options = {
					infra: result.getInfra,
					env: soajs.inputmaskData.env,
                    technology: soajs.inputmaskData.technology || 'vm',
					params: {
						vmName: soajs.inputmaskData.vmName,
						group: soajs.inputmaskData.group,
						region : soajs.inputmaskData.region,
						id : soajs.inputmaskData.instanceId
					},
					soajs: soajs
				};
				let technology = soajs.inputmaskData.technology;
				soajs.log.info(`VM Maintenance operation ${soajs.inputmaskData.operation} started!`);
				deployer.execute({ type: "infra", name: result.getInfra.name, technology: technology }, soajs.inputmaskData.operation, options, (err, res) => {
					if (err){
						soajs.log.error(err);
					}
					else {
						soajs.log.info(`Operation ${res.name}: ${res.status} at ${res.endTime}`);
					}
				});
				return cbMain(null, true);
			});
		});
	},

	/**
	 * Get virtual machine journalctl logs
	 *
	 * @param {Object} config
	 * @param {Object} soajs
	 * @param {Object} deployer
	 * @param {Function} cbMain
	 */
	"getLogVM": function (config, soajs, deployer, cbMain) {
		async.auto({
			"getEnvironment": (mCb) =>{
				if (!soajs.inputmaskData.env){
					return soajs.inputmaskData.env;
				}
				utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), (error, envRecord) => {
					checkIfError(soajs, mCb, { config: config, error: error || !envRecord, code: 600 }, mCb);
				});
			},
			"getInfra": (mCb) =>{
				soajs.inputmaskData.id = soajs.inputmaskData.infraId;
				BL.model.validateId(soajs, (err) => {
					checkIfError(soajs, mCb, {config: config, error: err, code: 490}, () => {
						let opts = {
							collection: infraColname,
							conditions: {
								_id: soajs.inputmaskData.id
							}
						};
						BL.model.findEntry(soajs, opts, function (err, infraRecord) {
							checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
								checkIfError(soajs, mCb, {
									config: config,
									error: !infraRecord,
									code: 600
								}, () => {
									return mCb(null, infraRecord);
								});
							});
						});
					});
				});
			}
		}, (error, result) => {
			checkIfError(soajs, cbMain, {config: config, error: error}, () => {
				let infraRecord = result.getInfra;
				let options = {
					soajs: soajs,
					infra: infraRecord,
					env: soajs.inputmaskData.env,
					params: {
						group: soajs.inputmaskData.group,
						vmName: soajs.inputmaskData.vmName.toLowerCase()
					}
				};

				if (soajs.inputmaskData.numberOfLines){
					options.params.numberOfLines = soajs.inputmaskData.numberOfLines;
				}
				deployer.execute({ type: "infra", name: infraRecord.name, technology: soajs.inputmaskData.technology }, 'getLogs', options, (error, logs) => {
					checkIfError(soajs, cbMain, {config: config, error: error}, () => {
						return cbMain(null, logs);
					});
				});
			});
		});
	}

};

module.exports = {
	"init": function (modelName, cb) {
		let modelPath;

		if (!modelName) {
			return cb(new Error("No Model Requested!"));
		}

		modelPath = __dirname + "/../../../models/" + modelName + ".js";
		return requireModel(modelPath, cb);

		/**
		 * checks if model file exists, requires it and returns it.
		 * @param filePath
		 * @param cb
		 */
		function requireModel (filePath, cb) {
			//check if file exist. if not return error
			fs.exists(filePath, (exists) => {
				if (!exists) {
					return cb(new Error("Requested Model Not Found!"));
				}

				BL.model = require(filePath);
				return cb(null, BL);
			});
		}
	}
};
<commit_msg>bug fix when requesting daemon soajs maintenance operation.<commit_after>'use strict';

const fs = require("fs");
const async = require('async');

const utils = require("../../../utils/utils.js");

function checkIfError(soajs, mainCb, data, cb) {
	utils.checkErrorReturn(soajs, mainCb, data, cb);
}

let infraColname = 'infra';
const BL = {
	model: null,

	/**
	 * Get logs of a container
	 *
	 * @param {Object} config
	 * @param {Object} soajs
	 * @param {Object} deployer
	 * @param {Function} cbMain
	 */
	"streamLogs": function (config, soajs, deployer, cbMain) {
		if((!soajs.inputmaskData.technology || soajs.inputmaskData.technology=== '' ) && !soajs.inputmaskData.taskId){
			return cbMain({code : 173, msg: "Invalid or Missing taskId in parameters!"});
		}

		async.auto({
			"getEnvironment": (mCb) =>{
				utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), (error, envRecord) => {
					checkIfError(soajs, mCb, { config: config, error: error || !envRecord, code: 600 }, () => {
						return mCb(null, envRecord);
					});
				});

			},
			"getInfra": (mCb) =>{
				//if infra id provided, use it
				//else pull based on env code
				if (soajs.inputmaskData.infraId) {
					soajs.inputmaskData.id = soajs.inputmaskData.infraId;
					BL.model.validateId(soajs, (err) => {
						checkIfError(soajs, mCb, {config: config, error: err, code: 490}, () => {
							let opts = {
								collection: infraColname,
								conditions: {
									_id: soajs.inputmaskData.id
								}
							};
							BL.model.findEntry(soajs, opts, function (err, infraRecord) {
								checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
									checkIfError(soajs, mCb, {
										config: config,
										error: !infraRecord,
										code: 600
									}, () => {
										return mCb(null, infraRecord);
									});
								});
							});
						});
					});
				}
				else {
					let opts = {
						collection: infraColname,
						conditions: {
							"deployments.environments": {"$in": [soajs.inputmaskData.env.toUpperCase()]}
						}
					};
					BL.model.findEntry(soajs, opts, function (err, infraRecord) {
						checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
							checkIfError(soajs, mCb, {config: config, error: !infraRecord, code: 600}, () => {
								return mCb(null, infraRecord);
							});
						});
					});
				}
			},
			"callDeployer": ["getEnvironment", "getInfra", (info, mCb) =>{
				let options = utils.buildDeployerOptions(info.getEnvironment, soajs, BL);
				options.infra = info.getInfra;
				//need to supply the stack if infra has more than drivers
				options.infra.stack = utils.getDeploymentFromInfra(options.infra, info.getEnvironment.code)[0];

				let technology = soajs.inputmaskData.technology || options.strategy;
				options.params = {
					id: soajs.inputmaskData.serviceId,
					taskId: soajs.inputmaskData.taskId,
					follow: soajs.inputmaskData.follow,
					filter: soajs.inputmaskData.filter || ""
				};

				deployer.execute({type: "infra", name: info.getInfra.name, technology: technology}, 'getContainerLogs', options, mCb);
				// TODO: handle logs Streaming once UI supports it
				// if(soajs.inputmaskData.follow) {
				// 	logs.on('data', (data) => {
				// 		console.log('---------------------------');
				// 		console.log(data.toString());
				// 		console.log('---------------------------');
				// 	});
				// }
				// else {
				// 	return cbMain(null, logs);
				// }
			}]
		}, (error, results) => {
			checkIfError(soajs, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, function () {
				return cbMain(null, results.callDeployer);
			});
		});
	},

	/**
	 * Perform a maintenance operation on a deployed SOAJS service
	 *
	 * @param {Object} config
	 * @param {Object} soajs
	 * @param {Object} deployer
	 * @param {Function} cbMain
	 */
	"maintenance": function (config, soajs, deployer, cbMain) {
		async.auto({
			"checkIfServiceOrDaemon": (mCb) =>{
				if(['service','daemon'].indexOf(soajs.inputmaskData.type) === -1){
					return mCb();
				}

				let serviceName = soajs.inputmaskData.serviceName;
				if(soajs.inputmaskData.type === 'daemon' && serviceName.indexOf("-") !== -1){
					serviceName = serviceName.split("-")[0];
				}
				let opts = {
					collection: (soajs.inputmaskData.type === 'service') ? 'services' : 'daemons',
					conditions: {
						name: serviceName
					}
				};
				BL.model.findEntry(soajs, opts, mCb);
			},
			"getEnvironment": (mCb) =>{
				utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), (error, envRecord) => {
					checkIfError(soajs, mCb, { config: config, error: error || !envRecord, code: 600 }, () => {
						return mCb(null, envRecord);
					});
				});
			},
			"getInfra": (mCb) =>{
				//if infra id provided, use it
				//else pull based on env code
				if (soajs.inputmaskData.infraId) {
					soajs.inputmaskData.id = soajs.inputmaskData.infraId;
					BL.model.validateId(soajs, (err) => {
						checkIfError(soajs, mCb, {config: config, error: err, code: 490}, () => {
							let opts = {
								collection: infraColname,
								conditions: {
									_id: soajs.inputmaskData.id
								}
							};
							BL.model.findEntry(soajs, opts, function (err, infraRecord) {
								checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
									checkIfError(soajs, mCb, {
										config: config,
										error: !infraRecord,
										code: 600
									}, () => {
										return mCb(null, infraRecord);
									});
								});
							});
						});
					});
				}
				else {
					let opts = {
						collection: infraColname,
						conditions: {
							"deployments.environments": {"$in": [soajs.inputmaskData.env.toUpperCase()]}
						}
					};
					BL.model.findEntry(soajs, opts, function (err, infraRecord) {
						checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
							checkIfError(soajs, mCb, {config: config, error: !infraRecord, code: 600}, () => {
								return mCb(null, infraRecord);
							});
						});
					});
				}
			},
			"callDeployer": ["checkIfServiceOrDaemon", "getEnvironment", "getInfra", (info, mCb) =>{
				let options = utils.buildDeployerOptions(info.getEnvironment, soajs, BL);
				options.infra = info.getInfra;
				//need to supply the stack if infra has more than drivers
				options.infra.stack = utils.getDeploymentFromInfra(options.infra, info.getEnvironment.code)[0];
				let technology = soajs.inputmaskData.technology || options.strategy;
				options.params = {
					toEnv: soajs.inputmaskData.env,
					id: soajs.inputmaskData.serviceId,
					network: config.network,
					operation: soajs.inputmaskData.operation,
					serviceName: soajs.inputmaskData.serviceName
				};

				if(info.checkIfServiceOrDaemon && info.checkIfServiceOrDaemon.port){
					options.params.maintenancePort = info.checkIfServiceOrDaemon.port + info.getEnvironment.services.config.ports.maintenanceInc;
				}

				soajs.log.info(`Maintenance operation ${soajs.inputmaskData.operation} started!`);
				deployer.execute({ type: "infra", name: info.getInfra.name, technology: technology }, 'maintenance', options, mCb);
			}]
		}, (error, results) => {
			checkIfError(soajs, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, function () {
				return cbMain(null, results.callDeployer);
			});
		});
	},

	/**
	 * Perform a maintenance operation on a deployed SOAJS service
	 *
	 * @param {Object} config
	 * @param {Object} soajs
	 * @param {Object} deployer
	 * @param {Function} cbMain
	 */
	"maintenanceVM": function (config, soajs, deployer, cbMain) {
		async.auto({
			"getEnvironment": (mCb) =>{
				if (!soajs.inputmaskData.env){
					return mCb(null, true);
				}
				utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), (error, envRecord) => {
					checkIfError(soajs, mCb, { config: config, error: error || !envRecord, code: 600 }, mCb);
				});
			},
			"getInfra": (mCb) =>{
				//if infra id provided, use it
				//else pull based on env code
				soajs.inputmaskData.id = soajs.inputmaskData.infraId;
				BL.model.validateId(soajs, (err) => {
					checkIfError(soajs, mCb, {config: config, error: err, code: 490}, () => {
						let opts = {
							collection: infraColname,
							conditions: {
								_id: soajs.inputmaskData.id
							}
						};
						BL.model.findEntry(soajs, opts, function (err, infraRecord) {
							checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
								checkIfError(soajs, mCb, {
									config: config,
									error: !infraRecord,
									code: 600
								}, () => {
									return mCb(null, infraRecord);
								});
							});
						});
					});
				});
			},
		}, (error, result) => {
			checkIfError(soajs, cbMain, { config: config, error: error, code: (error && error.code) ? error.code : 600 }, ()=>{
				let options = {
					infra: result.getInfra,
					env: soajs.inputmaskData.env,
                    technology: soajs.inputmaskData.technology || 'vm',
					params: {
						vmName: soajs.inputmaskData.vmName,
						group: soajs.inputmaskData.group,
						region : soajs.inputmaskData.region,
						id : soajs.inputmaskData.instanceId
					},
					soajs: soajs
				};
				let technology = soajs.inputmaskData.technology;
				soajs.log.info(`VM Maintenance operation ${soajs.inputmaskData.operation} started!`);
				deployer.execute({ type: "infra", name: result.getInfra.name, technology: technology }, soajs.inputmaskData.operation, options, (err, res) => {
					if (err){
						soajs.log.error(err);
					}
					else {
						soajs.log.info(`Operation ${res.name}: ${res.status} at ${res.endTime}`);
					}
				});
				return cbMain(null, true);
			});
		});
	},

	/**
	 * Get virtual machine journalctl logs
	 *
	 * @param {Object} config
	 * @param {Object} soajs
	 * @param {Object} deployer
	 * @param {Function} cbMain
	 */
	"getLogVM": function (config, soajs, deployer, cbMain) {
		async.auto({
			"getEnvironment": (mCb) =>{
				if (!soajs.inputmaskData.env){
					return soajs.inputmaskData.env;
				}
				utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), (error, envRecord) => {
					checkIfError(soajs, mCb, { config: config, error: error || !envRecord, code: 600 }, mCb);
				});
			},
			"getInfra": (mCb) =>{
				soajs.inputmaskData.id = soajs.inputmaskData.infraId;
				BL.model.validateId(soajs, (err) => {
					checkIfError(soajs, mCb, {config: config, error: err, code: 490}, () => {
						let opts = {
							collection: infraColname,
							conditions: {
								_id: soajs.inputmaskData.id
							}
						};
						BL.model.findEntry(soajs, opts, function (err, infraRecord) {
							checkIfError(soajs, mCb, {config: config, error: err, code: 600}, () => {
								checkIfError(soajs, mCb, {
									config: config,
									error: !infraRecord,
									code: 600
								}, () => {
									return mCb(null, infraRecord);
								});
							});
						});
					});
				});
			}
		}, (error, result) => {
			checkIfError(soajs, cbMain, {config: config, error: error}, () => {
				let infraRecord = result.getInfra;
				let options = {
					soajs: soajs,
					infra: infraRecord,
					env: soajs.inputmaskData.env,
					params: {
						group: soajs.inputmaskData.group,
						vmName: soajs.inputmaskData.vmName.toLowerCase()
					}
				};

				if (soajs.inputmaskData.numberOfLines){
					options.params.numberOfLines = soajs.inputmaskData.numberOfLines;
				}
				deployer.execute({ type: "infra", name: infraRecord.name, technology: soajs.inputmaskData.technology }, 'getLogs', options, (error, logs) => {
					checkIfError(soajs, cbMain, {config: config, error: error}, () => {
						return cbMain(null, logs);
					});
				});
			});
		});
	}

};

module.exports = {
	"init": function (modelName, cb) {
		let modelPath;

		if (!modelName) {
			return cb(new Error("No Model Requested!"));
		}

		modelPath = __dirname + "/../../../models/" + modelName + ".js";
		return requireModel(modelPath, cb);

		/**
		 * checks if model file exists, requires it and returns it.
		 * @param filePath
		 * @param cb
		 */
		function requireModel (filePath, cb) {
			//check if file exist. if not return error
			fs.exists(filePath, (exists) => {
				if (!exists) {
					return cb(new Error("Requested Model Not Found!"));
				}

				BL.model = require(filePath);
				return cb(null, BL);
			});
		}
	}
};
<|endoftext|>


<commit_before>import { window, document } from 'ssr-window';
import $ from 'dom7';
import Template7 from 'template7';
import Utils from '../../utils/utils';
import vdom from './vdom';
import patch from './patch';

let counter = 0;

function renderEsTemplate(template, id) {
  const callbackName = `f7_component_es_template${id || new Date().getTime()}`;

  const scriptContent = `
    window.${callbackName} = function () {
      return \`${template}\`;
    }
  `;
  // Insert Script El
  const scriptEl = document.createElement('script');
  scriptEl.innerHTML = scriptContent;
  $('head').append(scriptEl);

  // Render function
  const render = window[callbackName];

  // Remove Script El
  $(scriptEl).remove();
  delete window[callbackName];

  return render;
}

class Framework7Component {
  constructor(app, options, extendContext = {}) {
    const id = `${Utils.now()}${counter}`;
    const self = Utils.merge(
      this,
      extendContext,
      {
        $,
        $$: $,
        $dom7: $,
        $app: app,
        $options: Utils.extend({ id }, options),
      }
    );
    const { $options } = self;
    counter += 1;

    // Root data and methods
    Object.defineProperty(self, '$root', {
      enumerable: true,
      configurable: true,
      get() {
        return Utils.merge({}, app.data, app.methods);
      },
      set() {},
    });

    // Apply context
    ('beforeCreate created beforeMount mounted beforeDestroy destroyed updated').split(' ').forEach((cycleKey) => {
      if ($options[cycleKey]) $options[cycleKey] = $options[cycleKey].bind(self);
    });

    if ($options.data) {
      $options.data = $options.data.bind(self);
      // Data
      Utils.extend(self, $options.data());
    }
    if ($options.render) $options.render = $options.render.bind(self);
    if ($options.methods) {
      Object.keys($options.methods).forEach((methodName) => {
        self[methodName] = $options.methods[methodName].bind(self);
      });
    }

    // Bind Events
    if ($options.on) {
      Object.keys($options.on).forEach((eventName) => {
        $options.on[eventName] = $options.on[eventName].bind(self);
      });
    }
    if ($options.once) {
      Object.keys($options.once).forEach((eventName) => {
        $options.once[eventName] = $options.once[eventName].bind(self);
      });
    }

    // Before create hook
    if ($options.beforeCreate) $options.beforeCreate();

    // Render
    let html = self.$render();

    // Make Dom
    if (html && typeof html === 'string') {
      html = html.trim();
      self.$vnode = vdom(html, self, app, true);
      self.el = document.createElement('div');
      patch(self.el, self.$vnode);
    } else if (html) {
      self.el = html;
    }
    self.$el = $(self.el);

    // Set styles scope ID
    if ($options.style) {
      self.$styleEl = document.createElement('style');
      self.$styleEl.innerHTML = $options.style;
      if ($options.styleScoped) {
        self.el.setAttribute('data-scope', $options.id);
      }
    }

    self.$attachEvents();

    // Created callback
    if ($options.created) $options.created();

    // Store component instance
    self.el.f7Component = self;

    return self;
  }

  $attachEvents() {
    const self = this;
    const { $options, $el } = self;
    if ($options.on) {
      Object.keys($options.on).forEach((eventName) => {
        $el.on(Utils.eventNameToColonCase(eventName), $options.on[eventName]);
      });
    }
    if ($options.once) {
      Object.keys($options.once).forEach((eventName) => {
        $el.once(Utils.eventNameToColonCase(eventName), $options.once[eventName]);
      });
    }
  }

  $detachEvents() {
    const self = this;
    const { $options, $el } = self;
    if ($options.on) {
      Object.keys($options.on).forEach((eventName) => {
        $el.off(Utils.eventNameToColonCase(eventName), $options.on[eventName]);
      });
    }
    if ($options.once) {
      Object.keys($options.once).forEach((eventName) => {
        $el.off(Utils.eventNameToColonCase(eventName), $options.once[eventName]);
      });
    }
  }

  $render() {
    const self = this;
    const { $options } = self;
    let html = '';
    if ($options.render) {
      html = $options.render();
    } else if ($options.template) {
      if (typeof $options.template === 'string') {
        if ($options.templateType === 't7' || !$options.templateType) {
          try {
            html = Template7.compile($options.template)(self);
          } catch (err) {
            throw err;
          }
        }
        if ($options.templateType === 'es') {
          $options.render = renderEsTemplate($options.template, $options.id).bind(self);
          html = $options.render();
        }
      } else {
        // Supposed to be function
        html = $options.template(self);
      }
    }
    return html;
  }

  $forceUpdate() {
    const self = this;
    let html = self.$render();

    // Make Dom
    if (html && typeof html === 'string') {
      html = html.trim();
      const newVNode = vdom(html, self, self.$app);
      self.$vnode = patch(self.$vnode, newVNode);
    }
  }

  $setState(mergeState) {
    const self = this;
    Utils.merge(self, mergeState);
    self.$forceUpdate();
  }

  $mount(mountMethod) {
    const self = this;
    if (self.$options.beforeMount) self.$options.beforeMount();
    if (self.$styleEl) $('head').append(self.$styleEl);
    if (mountMethod) mountMethod(self.el);
    if (self.$options.mounted) self.$options.mounted();
  }

  $destroy() {
    const self = this;
    if (self.$options.beforeDestroy) self.$options.beforeDestroy();
    if (self.$styleEl) $(self.$styleEl).remove();
    self.$detachEvents();
    if (self.$options.destroyed) self.$options.destroyed();
    if (window[`f7_component_es_template${self.$options.id}`]) {
      delete window[`f7_component_es_template${self.$options.id}`];
    }
    // Delete component instance
    if (self.el && self.el.f7Component) {
      self.el.f7Component = null;
      delete self.el.f7Component;
    }
    // Patch with empty node
    if (self.$vnode) {
      self.$vnode = patch(self.$vnode, { sel: self.$vnode.sel, data: {} });
    }
    Utils.deleteProps(self);
  }
}

export default Framework7Component;
<commit_msg>Core: Router component - use Proxy for props update<commit_after>import { window, document } from 'ssr-window';
import $ from 'dom7';
import Template7 from 'template7';
import Utils from '../../utils/utils';
import vdom from './vdom';
import patch from './patch';

let counter = 0;

function renderEsTemplate(template, id) {
  const callbackName = `f7_component_es_template${id || new Date().getTime()}`;

  const scriptContent = `
    window.${callbackName} = function () {
      return \`${template}\`;
    }
  `;
  // Insert Script El
  const scriptEl = document.createElement('script');
  scriptEl.innerHTML = scriptContent;
  $('head').append(scriptEl);

  // Render function
  const render = window[callbackName];

  // Remove Script El
  $(scriptEl).remove();
  delete window[callbackName];

  return render;
}

class Framework7Component {
  constructor(app, options, extendContext = {}) {
    const id = `${Utils.now()}${counter}`;
    const self = Utils.merge(
      this,
      extendContext,
      {
        $,
        $$: $,
        $dom7: $,
        $app: app,
        $options: Utils.extend({ id }, options),
      }
    );
    const { $options } = self;
    counter += 1;

    // Root data and methods
    Object.defineProperty(self, '$root', {
      enumerable: true,
      configurable: true,
      get() {
        let root = Utils.merge({}, app.data, app.methods);
        if (window && window.Proxy) {
          root = new window.Proxy(root, {
            set(target, name, val) {
              app.data[name] = val;
            },
            deleteProperty(target, name) {
              delete app.data[name];
              delete app.methods[name];
            },
            has(target, name) {
              return (name in app.data || name in app.methods);
            },
          });
        }
        return root;
      },
      set() {},
    });

    // Apply context
    ('beforeCreate created beforeMount mounted beforeDestroy destroyed updated').split(' ').forEach((cycleKey) => {
      if ($options[cycleKey]) $options[cycleKey] = $options[cycleKey].bind(self);
    });

    if ($options.data) {
      $options.data = $options.data.bind(self);
      // Data
      Utils.extend(self, $options.data());
    }
    if ($options.render) $options.render = $options.render.bind(self);
    if ($options.methods) {
      Object.keys($options.methods).forEach((methodName) => {
        self[methodName] = $options.methods[methodName].bind(self);
      });
    }

    // Bind Events
    if ($options.on) {
      Object.keys($options.on).forEach((eventName) => {
        $options.on[eventName] = $options.on[eventName].bind(self);
      });
    }
    if ($options.once) {
      Object.keys($options.once).forEach((eventName) => {
        $options.once[eventName] = $options.once[eventName].bind(self);
      });
    }

    // Before create hook
    if ($options.beforeCreate) $options.beforeCreate();

    // Render
    let html = self.$render();

    // Make Dom
    if (html && typeof html === 'string') {
      html = html.trim();
      self.$vnode = vdom(html, self, app, true);
      self.el = document.createElement('div');
      patch(self.el, self.$vnode);
    } else if (html) {
      self.el = html;
    }
    self.$el = $(self.el);

    // Set styles scope ID
    if ($options.style) {
      self.$styleEl = document.createElement('style');
      self.$styleEl.innerHTML = $options.style;
      if ($options.styleScoped) {
        self.el.setAttribute('data-scope', $options.id);
      }
    }

    self.$attachEvents();

    // Created callback
    if ($options.created) $options.created();

    // Store component instance
    self.el.f7Component = self;

    return self;
  }

  $attachEvents() {
    const self = this;
    const { $options, $el } = self;
    if ($options.on) {
      Object.keys($options.on).forEach((eventName) => {
        $el.on(Utils.eventNameToColonCase(eventName), $options.on[eventName]);
      });
    }
    if ($options.once) {
      Object.keys($options.once).forEach((eventName) => {
        $el.once(Utils.eventNameToColonCase(eventName), $options.once[eventName]);
      });
    }
  }

  $detachEvents() {
    const self = this;
    const { $options, $el } = self;
    if ($options.on) {
      Object.keys($options.on).forEach((eventName) => {
        $el.off(Utils.eventNameToColonCase(eventName), $options.on[eventName]);
      });
    }
    if ($options.once) {
      Object.keys($options.once).forEach((eventName) => {
        $el.off(Utils.eventNameToColonCase(eventName), $options.once[eventName]);
      });
    }
  }

  $render() {
    const self = this;
    const { $options } = self;
    let html = '';
    if ($options.render) {
      html = $options.render();
    } else if ($options.template) {
      if (typeof $options.template === 'string') {
        if ($options.templateType === 't7' || !$options.templateType) {
          try {
            html = Template7.compile($options.template)(self);
          } catch (err) {
            throw err;
          }
        }
        if ($options.templateType === 'es') {
          $options.render = renderEsTemplate($options.template, $options.id).bind(self);
          html = $options.render();
        }
      } else {
        // Supposed to be function
        html = $options.template(self);
      }
    }
    return html;
  }

  $forceUpdate() {
    const self = this;
    let html = self.$render();

    // Make Dom
    if (html && typeof html === 'string') {
      html = html.trim();
      const newVNode = vdom(html, self, self.$app);
      self.$vnode = patch(self.$vnode, newVNode);
    }
  }

  $setState(mergeState) {
    const self = this;
    Utils.merge(self, mergeState);
    self.$forceUpdate();
  }

  $mount(mountMethod) {
    const self = this;
    if (self.$options.beforeMount) self.$options.beforeMount();
    if (self.$styleEl) $('head').append(self.$styleEl);
    if (mountMethod) mountMethod(self.el);
    if (self.$options.mounted) self.$options.mounted();
  }

  $destroy() {
    const self = this;
    if (self.$options.beforeDestroy) self.$options.beforeDestroy();
    if (self.$styleEl) $(self.$styleEl).remove();
    self.$detachEvents();
    if (self.$options.destroyed) self.$options.destroyed();
    if (window[`f7_component_es_template${self.$options.id}`]) {
      delete window[`f7_component_es_template${self.$options.id}`];
    }
    // Delete component instance
    if (self.el && self.el.f7Component) {
      self.el.f7Component = null;
      delete self.el.f7Component;
    }
    // Patch with empty node
    if (self.$vnode) {
      self.$vnode = patch(self.$vnode, { sel: self.$vnode.sel, data: {} });
    }
    Utils.deleteProps(self);
  }
}

export default Framework7Component;
<|endoftext|>


<commit_before>/**
 * Created by pascalbrewing on 08/10/14.
 */
var util = require('util');
var chalk = require('chalk');
var _ = require('lodash');
var Table = require('cli-table');
var figures = require('figures');
var serverconfig = require('mcaprc');
/**
 * @example 80 or 9200 min 2 ,max 4
 * @type {RegExp}
 */
var portRegex = /^(\d){2}$|(\d){4}$/;
/**
 * url Pattern allowed
 * @example https://localkllk:9100/blubber&id=234 http://localkllk.de/blubber&id=234
 * @type {RegExp}
 */
var urlPattern = /(http|https):\/\/[\w-]+(\.[\w-]+)|(\:[0-9])([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/;
/**
 * allow a-Z 0-9 for the server name
 * @type {RegExp}
 */
var stringNumberPattern = /^[a-zA-Z\s]|[0-9\s]+$/;
/**
 * check if the value not empty
 * @param {string} label
 * @returns {Function}
 */
var notEmptyValidate = function (label) {
    return function (value) {
        if ( value ) {
            return true;
        }
        return util.format('%s can not be empty', label);
    }
};
/**
 * check if default Server or not
 * @param {string} defaultName
 * @param {string} serverName
 * @returns {*}
 */
function _isDefault(defaultName, serverName) {

    if ( defaultName === serverName ) {
        return chalk.green(figures.radioOn);
    } else {
        return chalk.red(figures.cross);
    }
}
/**
 * prepare the table formatting
 * @link https://www.npmjs.org/package/cli-table
 * @type {{top: string, top-mid: string, top-left: string, top-right: string, bottom: string, bottom-mid: string,
 *   bottom-left: string, bottom-right: string, left: string, left-mid: string, mid: string, mid-mid: string, right:
 *   string, right-mid: string, middle: string}}
 */
var tableChars = {
    'top'         : '═',
    'top-mid'     : '╤',
    'top-left'    : '╔',
    'top-right'   : '╗',
    'bottom'      : '═',
    'bottom-mid'  : '╧',
    'bottom-left' : '╚',
    'bottom-right': '╝',
    'left'        : '║',
    'left-mid'    : '╟',
    'mid'         : '─',
    'mid-mid'     : '┼',
    'right'       : '║',
    'right-mid'   : '╢',
    'middle'      : '│'
};
/**
 * get the all servers from the mcaprc
 *
 * @param {object} config
 */
function displayTable(config) {
    // if length 1 we have a empty json with only {default:''}
    // first time
    if ( typeof config === 'object' && Object.keys(config.server).length > 0 ) {
        var keys = _.keys(config.server);
        var table = new Table(
            {
                head     : [ chalk.magenta("Server"), chalk.magenta("Default"), chalk.magenta("Option"), chalk.magenta("Value") ],
                chars    : tableChars,
                colWidth : [ 200, 200, 200, 200 ],
                colAligns: [ 'left', 'middle', 'left', 'left' ]
            }
        );
        // get the server from the Json
        keys.forEach(function (key) {
            var inverseKeys = _.keys(config[ 'server' ][ key ]);
            if ( key !== serverconfig.default_server ) {

                if ( inverseKeys.length > 0 ) {
                    var i = 0;
                    inverseKeys.forEach(function (subkey, count) {
                        if ( key !== serverconfig.default_server ) {
                            table.push(
                                [
                                    i === 0 ? chalk.cyan(key)
                                        : '',
                                    i === 0 ? _isDefault(config[ serverconfig.default_server ], key)
                                        : '',

                                    chalk.yellow(inverseKeys[ count ]),

                                    config[ 'server' ][ key ][ subkey ] !== '' ? chalk.green(config[ 'server' ][ key ][ subkey ])
                                        : chalk.red('na')
                                ]
                            );
                            i++;
                        }
                    });
                }
            }
        });
        console.log(table.toString());
    } else {
        console.log(chalk.bgYellow(chalk.red(figures.warning) + chalk.black('Looks like no Server was defined. ')));
    }
}
module.exports = {
    displayTable    : displayTable,
    notEmptyValidate: notEmptyValidate,
    pattern:{
        url:urlPattern,
        stringNumber:stringNumberPattern,
        port:portRegex
    },
    tableChars:tableChars
};
<commit_msg>add missing ;<commit_after>/**
 * Created by pascalbrewing on 08/10/14.
 */
var util = require('util');
var chalk = require('chalk');
var _ = require('lodash');
var Table = require('cli-table');
var figures = require('figures');
var serverconfig = require('mcaprc');
/**
 * @example 80 or 9200 min 2 ,max 4
 * @type {RegExp}
 */
var portRegex = /^(\d){2}$|(\d){4}$/;
/**
 * url Pattern allowed
 * @example https://localkllk:9100/blubber&id=234 http://localkllk.de/blubber&id=234
 * @type {RegExp}
 */
var urlPattern = /(http|https):\/\/[\w-]+(\.[\w-]+)|(\:[0-9])([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/;
/**
 * allow a-Z 0-9 for the server name
 * @type {RegExp}
 */
var stringNumberPattern = /^[a-zA-Z\s]|[0-9\s]+$/;
/**
 * check if the value not empty
 * @param {string} label
 * @returns {Function}
 */
var notEmptyValidate = function (label) {
    return function (value) {
        if ( value ) {
            return true;
        }
        return util.format('%s can not be empty', label);
    };
};
/**
 * check if default Server or not
 * @param {string} defaultName
 * @param {string} serverName
 * @returns {*}
 */
function _isDefault(defaultName, serverName) {

    if ( defaultName === serverName ) {
        return chalk.green(figures.radioOn);
    } else {
        return chalk.red(figures.cross);
    }
}
/**
 * prepare the table formatting
 * @link https://www.npmjs.org/package/cli-table
 * @type {{top: string, top-mid: string, top-left: string, top-right: string, bottom: string, bottom-mid: string,
 *   bottom-left: string, bottom-right: string, left: string, left-mid: string, mid: string, mid-mid: string, right:
 *   string, right-mid: string, middle: string}}
 */
var tableChars = {
    'top'         : '═',
    'top-mid'     : '╤',
    'top-left'    : '╔',
    'top-right'   : '╗',
    'bottom'      : '═',
    'bottom-mid'  : '╧',
    'bottom-left' : '╚',
    'bottom-right': '╝',
    'left'        : '║',
    'left-mid'    : '╟',
    'mid'         : '─',
    'mid-mid'     : '┼',
    'right'       : '║',
    'right-mid'   : '╢',
    'middle'      : '│'
};
/**
 * get the all servers from the mcaprc
 *
 * @param {object} config
 */
function displayTable(config) {
    // if length 1 we have a empty json with only {default:''}
    // first time
    if ( typeof config === 'object' && Object.keys(config.server).length > 0 ) {
        var keys = _.keys(config.server);
        var table = new Table(
            {
                head     : [ chalk.magenta("Server"), chalk.magenta("Default"), chalk.magenta("Option"), chalk.magenta("Value") ],
                chars    : tableChars,
                colWidth : [ 200, 200, 200, 200 ],
                colAligns: [ 'left', 'middle', 'left', 'left' ]
            }
        );
        // get the server from the Json
        keys.forEach(function (key) {
            var inverseKeys = _.keys(config[ 'server' ][ key ]);
            if ( key !== serverconfig.default_server ) {

                if ( inverseKeys.length > 0 ) {
                    var i = 0;
                    inverseKeys.forEach(function (subkey, count) {
                        if ( key !== serverconfig.default_server ) {
                            table.push(
                                [
                                    i === 0 ? chalk.cyan(key)
                                        : '',
                                    i === 0 ? _isDefault(config[ serverconfig.default_server ], key)
                                        : '',

                                    chalk.yellow(inverseKeys[ count ]),

                                    config[ 'server' ][ key ][ subkey ] !== '' ? chalk.green(config[ 'server' ][ key ][ subkey ])
                                        : chalk.red('na')
                                ]
                            );
                            i++;
                        }
                    });
                }
            }
        });
        console.log(table.toString());
    } else {
        console.log(chalk.bgYellow(chalk.red(figures.warning) + chalk.black('Looks like no Server was defined. ')));
    }
}
module.exports = {
    displayTable    : displayTable,
    notEmptyValidate: notEmptyValidate,
    pattern:{
        url:urlPattern,
        stringNumber:stringNumberPattern,
        port:portRegex
    },
    tableChars:tableChars
};
<|endoftext|>