hackedteam/rcs-console

View on GitHub
src/it/ht/rcs/console/operations/view/configuration/ConfigurationActionBar.mxml

Summary

Maintainability
Test Coverage
<?xml version="1.0" encoding="utf-8"?>
<actionbar:ActionBar xmlns:fx="http://ns.adobe.com/mxml/2009"
                     xmlns:s="library://ns.adobe.com/flex/spark"
                     xmlns:mx="library://ns.adobe.com/flex/mx"
                     xmlns:actionbar="it.ht.rcs.console.main.actionbar.*"
                     addedToStage="onAddedToStage(event)">

  <s:HGroup visible="{section.stateManager.selectedFactory != null}" gap="0"
            includeInLayout="{section.stateManager.selectedFactory != null}">
    <s:Button label="{R.get('BUILD')}" click="build(event)" icon="@Embed('/img/NEW/build.png')" enabled="{LicenseManager.instance.archive == 0 &amp;&amp; Console.currentSession.user.is_tech_build() &amp;&amp; section.stateManager.selectedFactory.good}"/>
    <actionbar:Separator/>
  </s:HGroup>
  
  <s:Button label="{R.get('SAVE')}" click="onSave()" icon="@Embed('/img/NEW/save.png')" enabled="{Console.currentSession.user.is_tech_config()}"/>
  <s:Button label="{R.get('EXPORT')}" click="export(event)" icon="@Embed('/img/NEW/export.png')"/>
  <s:Button label="{R.get('IMPORT')}" click="importFile(event)" icon="@Embed('/img/NEW/import.png')" enabled="{Console.currentSession.user.is_tech_config()}"/>
  <s:Button label="{R.get('TEMPLATES')}" click="openTemplatePanel(event)" icon="@Embed('/img/NEW/template.png')" enabled="{Console.currentSession.user.is_tech_config()}"/>
  
  <actionbar:Separator/>

  <s:HGroup visible="{configView.currentState == 'advanced'}" gap="0"
            includeInLayout="{configView.currentState == 'advanced'}">
    <s:Button label="{R.get('ADD_EVENT')}" click="addEvent(event)" icon="@Embed('/img/NEW/newEvent.png')" enabled="{Console.currentSession.user.is_tech_config()}"/>
    <s:Button label="{R.get('ADD_ACTION')}" click="addAction(event)" icon="@Embed('/img/NEW/newAction.png')" enabled="{Console.currentSession.user.is_tech_config()}"/>
    
    <s:Button label="{R.get('EDIT')}" click="onEdit()"
              enabled="{configView.advanced.graph.selectedElement != null &amp;&amp; Console.currentSession.user.is_tech_config()}" 
              icon="@Embed('/img/NEW/edit.png')"/>
    <s:Button label="{R.get('DELETE')}" click="onDelete()"
              enabled="{configView.advanced.graph.selectedElement != null &amp;&amp; !(configView.advanced.graph.selectedElement is ModuleRenderer) &amp;&amp; Console.currentSession.user.is_tech_config()}" 
              icon="@Embed('/img/NEW/delete_32.png')"/>
    <s:Button label="{R.get('EDIT_GLOBALS')}" click="editGlobals(event)" icon="@Embed('/img/NEW/globals.png')" enabled="{Console.currentSession.user.is_tech_config()}"/>
    <actionbar:Separator/>
    <s:Button label="{R.get('BACK_TO_BASIC')}" click="backToBasic(event)" icon="@Embed('/img/NEW/basic.png')" enabled="{Console.currentSession.user.is_tech_config()}"/>
    <actionbar:Separator/>  
    <s:Button id="collapse" label="{configView.advanced.graph.collapsed ? R.get('EXPAND'): R.get('COLLAPSE')}" click="onCollapseAll()" icon="{configView.advanced.graph.collapsed ? expandIcon : collapseIcon}"/>
  </s:HGroup>

  <s:HGroup visible="{configView.currentState == 'basic'}" gap="0"
            includeInLayout="{configView.currentState == 'basic'}">

    <s:Button label="{R.get('CONFIG_ADVANCED')}" click="goToAdvanced(event)"
              icon="@Embed('/img/NEW/config_32.png')" enabled="{Console.currentSession.user.is_tech_config() &amp;&amp; (configView.section.stateManager.selectedFactory || configView.section.stateManager.selectedAgent.level!='soldier') }"/>
  </s:HGroup>
  
  <s:HGroup visible="{configView.currentState == 'advanced'}" gap="0">
    <actionbar:Separator/>

  </s:HGroup>
  
  <fx:Script>
    <![CDATA[
      import flash.net.SharedObject;
      
      import it.ht.rcs.console.DefaultConfigBuilder;
      import it.ht.rcs.console.agent.controller.AgentManager;
      import it.ht.rcs.console.agent.model.Agent;
      import it.ht.rcs.console.agent.model.Config;
      import it.ht.rcs.console.monitor.controller.LicenseManager;
      import it.ht.rcs.console.network.controller.CollectorManager;
      import it.ht.rcs.console.network.model.Collector;
      import it.ht.rcs.console.notifications.NotificationPopup;
      import it.ht.rcs.console.operations.view.OperationsSection;
      import it.ht.rcs.console.operations.view.agents.build.BuildForm;
      import it.ht.rcs.console.operations.view.configuration.advanced.forms.globals.GlobalsForm;
      import it.ht.rcs.console.operations.view.configuration.advanced.renderers.ModuleRenderer;
      import it.ht.rcs.console.operations.view.configuration.template.TemplateView;
      import it.ht.rcs.console.utils.AlertPopUp;
      
      import locale.R;
      
      import mx.collections.ArrayCollection;
      import mx.collections.ListCollectionView;
      import mx.controls.Alert;
      import mx.core.UIComponent;
      import mx.events.CloseEvent;
      import mx.managers.PopUpManager;
      import mx.rpc.events.FaultEvent;
      import mx.rpc.events.ResultEvent;
      
      import spark.primitives.Rect;
      
      [Embed('/img/NEW/expand_all.png')]
      private static const expandIcon:Class;
      [Embed('/img/NEW/collapse_all.png')]
      private static const collapseIcon:Class;
      
      [Bindable]
      public var section:OperationsSection;
      [Bindable]
      public var configView:ConfigurationView;
      
      private var securitySettings:SharedObject;
      
      private function build(event:MouseEvent):void
      {
        var userId:String=Console.currentSession.user._id;
        var appMajorVersion:String=Console.rcsVersion.substr(0,3);
        try
        {
          securitySettings = SharedObject.getLocal("securitySettings_"+appMajorVersion);
        }
        catch (error:Error)
        {
          trace("SharedObject Error:"+error.toString());
          return;
        }
        if(!securitySettings.data[userId])
        {
          var sW:SecurityWarning=PopUpManager.createPopUp(root, SecurityWarning, true) as SecurityWarning;
          sW.addEventListener("close", onWarningClose)
          PopUpManager.centerPopUp(sW);
        }
        else{
          doBuild()
        }
      }
      
      private function onWarningClose(e:Event):void
      {
        var userId:String=Console.currentSession.user._id;
        var sW:SecurityWarning=e.currentTarget as SecurityWarning;
        securitySettings.data[userId]=sW.doNotShow;
        doBuild();
      }
      
      private function doBuild():void
      {
        if(saveConfig() !=null)
        {
          var b:BuildForm = PopUpManager.createPopUp(root, BuildForm, true) as BuildForm;
          b.configView=configView;
          b.factory = section.stateManager.selectedFactory;
          PopUpManager.centerPopUp(b);
        }
      }
      
      private function onAddedToStage(event:Event):void
      {
        configView = parent as ConfigurationView;
      }
      
      private function onSave():void
      {
        if(saveConfig(goBackToList) !=null)
        {
          NotificationPopup.showNotification(R.get('CONFIG_SAVED'), 2)
        }
       
      }
      
      private function saveConfig(callback:Function = null):Object
      {
       if(configView.currentState=='basic')
       {
         if(configView.basic.sync.host.selectedItem==null && configView.basic.sync.selected)
         {
           AlertPopUp.show(R.get('MISSING_COLLECTOR'))
           return null;
         }
       }
        var config:Object = getConfig();
        if (config == null) return null;
        
    
        var a:Agent = configView.section.stateManager.selectedFactory || configView.section.stateManager.selectedAgent;
        
        //get the host provided from the first sync action
        var host:String="";
        if (config.actions)
        {
          primary: for (var ac:int=0; ac < config.actions.length; ac++)
          {
            for (var sa:int=0; sa < config.actions[ac].subactions.length; sa++)
            {
              if (config.actions[ac].subactions[sa].action == "synchronize")
              {
                host=config.actions[ac].subactions[sa].host;
                break primary;
              }
            }
          }
        }
        
        //get the matching collector from the collector list
        var collectors:ListCollectionView=CollectorManager.instance.getView();
        var collector:Collector;
        var found:Boolean;
        for(var i:int=0;i<collectors.length;i++)
        {
          collector=collectors.getItemAt(i) as Collector;
          if(collector.name==host || collector.address==host)
          {
            found=true;
            break;
          }
        }
        //the provided host string doesn't match any collector
        if(!found && host!="" && !LicenseManager.instance.hostname_sync)
        {
          AlertPopUp.show(R.get('MISSING_COLLECTOR')) //Custom message??
          return null
        }
        
        //if collector is found check if good or bad according to Agent
        
        //must be bad
        
        if(!collector)
        {
          AlertPopUp.show(R.get('INVALID_COLLECTOR'))
          return null;
        }
        if(!a.good && collector.good && host!="")
        {
         AlertPopUp.show(R.get('INVALID_COLLECTOR'))
          return null;
        }
        //must be good
        if(a.good && !collector.good && host!="")
        {
          AlertPopUp.show(R.get('INVALID_COLLECTOR'))
          return null;
        }
        if(Console.currentSession.user.is_tech_config())
        {
        AgentManager.instance.addConfig(a, JSON.stringify(config), callback, faultCallback);
        }
        configView.updateOriginalConfig(config);
      
        return config;
      }
      
      private function faultCallback(e:FaultEvent):void
      {
        AlertPopUp.show(String(e.fault.content))
      }
      
      private function goBackToList(c:Config):void
      {
        if (configView.section.stateManager.selectedAgent != null)
          section.stateManager.setState('agentConfigList');
      }
      
      private function onEdit():void
      {
        var element:* = configView.advanced.graph.selectedElement;
        if (element != null && element.hasOwnProperty('onDoubleClick'))
          element.onDoubleClick(null);
      }
      
      private function onDelete():void
      {
        var element:* = configView.advanced.graph.selectedElement;
        if (element != null && element.hasOwnProperty('deleteEvent'))
          element.deleteEvent();
        else if (element != null && element.hasOwnProperty('deleteAction'))
          element.deleteAction();
        else if (element != null && element.hasOwnProperty('deleteConnection'))
          element.deleteConnection();
      }
      
      private function importFile(e:MouseEvent):void
      {
        var f:File = new File();
        f.addEventListener(Event.SELECT, function(e:Event):void {
          var fileStream:FileStream = new FileStream();
          fileStream.open(e.target as File, FileMode.READ);
          var config:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
          var configAsObject:Object = JSON.parse(config);
          //configAsObject.globals.type
          
          //check if the imported config is same type
          var a:Agent = configView.section.stateManager.selectedFactory || configView.section.stateManager.selectedAgent;
          var currentType:String=a.type.toLowerCase();
          var importedType:String=configAsObject.globals.type.toLowerCase();
          if(currentType!=importedType)
          {
            AlertPopUp.show(R.get('CONFIG_IMPORT_INVALID_TYPE',[currentType, importedType]));
            return;
          }
          configView.configAsObject = configAsObject;
          configView.displayConfig(true);
        });
        f.browseForOpen('Open config', [new FileFilter('Config (*.json)', '*.json')]);
      }
      
      private function export(event:MouseEvent):void
      {
        //var config:Object = saveConfig();
        var config:Object=getConfig()
        
        var f:File = new File();
        f.addEventListener(Event.SELECT, function(e:Event):void {
          var file:File = e.target as File;
          if (file.nativePath.indexOf('.json') == -1)
            file.nativePath = file.nativePath + '.json';
          var fileStream:FileStream = new FileStream();
          fileStream.open(file, FileMode.WRITE);
          fileStream.writeUTFBytes(PrettyPrinter.prettyPrint(config));
          fileStream.close();
          file.openWithDefaultApplication();
        });
        f.browseForSave('Save config');
      }
      
      private function getConfig():Object
      {
        var config:Object = null;
        if (configView.currentState == 'advanced')
          config = configView.advanced.getConfig();
        else if (configView.basic.isValid())
          config = configView.basic.getConfig();
        
        return config;
      }
      
      private function addAction(event:MouseEvent):void
      {
        configView.advanced.addAction(null);
      }
      
      private function addEvent(event:MouseEvent):void
      {
        configView.advanced.addEvent(null);
      }
      
      private function editGlobals(event:MouseEvent):void
      {
        var popup:GlobalsForm = PopUpManager.createPopUp(root, GlobalsForm, true) as GlobalsForm;
        var a:Agent = configView.section.stateManager.selectedFactory || configView.section.stateManager.selectedAgent;
        popup.globals = configView.configAsObject.globals;
        popup.agent=a;
        PopUpManager.centerPopUp(popup);
      }
      
      private function goToAdvanced(event:MouseEvent):void
      {
        AlertPopUp.show(R.get('GO_TO_ADVANCED_WARNING'), R.get('CONFIRM'),
          AlertPopUp.YES|AlertPopUp.NO, null,
          function(e:CloseEvent):void {
            if (e.detail == AlertPopUp.YES)
              doGoToAdvanced();
          }, null, AlertPopUp.NO);
      }
      
      private function doGoToAdvanced():void
      {
        configView.basic.config.globals.advanced = true;
        saveConfig();
        
        configView.currentState = 'advanced';
        configView.advanced.config = configView.basic.config;
        configView.advanced.displayConfig();
      }
      
      private function onCollapseAll():void
      {
        configView.advanced.graph.collapsed = !configView.advanced.graph.collapsed;
        configView.advanced.config.globals.collapsed = configView.advanced.graph.collapsed;
        configView.advanced.graph.rebuildGraph();
        collapse.label = configView.advanced.graph.collapsed ? R.get('EXPAND') : R.get('COLLAPSE');
        collapse.iconDisplay.source = configView.advanced.graph.collapsed ? expandIcon : collapseIcon;
      }
      
      private function backToBasic(event:MouseEvent):void
      {
        AlertPopUp.show(R.get('BACK_TO_BASIC_WARNING'), R.get('CONFIRM'),
          AlertPopUp.YES|AlertPopUp.NO, null,
          function(e:CloseEvent):void {
            if (e.detail == AlertPopUp.YES)
              doBackToBasic();
          }, null, AlertPopUp.NO);
      }
      
      private function doBackToBasic():void
      {
        var a:Agent = configView.section.stateManager.selectedFactory || configView.section.stateManager.selectedAgent;
        configView.currentState = 'basic';
        var newConfig:Object = DefaultConfigBuilder.getDefaultConfig(a);
        if (a._kind == 'agent')
          DefaultConfigBuilder.cleanPlatformConfig(a.platform, newConfig);
          configView.basic.config = newConfig;
          configView.basic.displayConfig();
      }
      
      private function onTemplateLoad(e:Event):void
      {
        var loadedConfig:Object=e.currentTarget.config;
        configView.configAsObject = loadedConfig;
        configView.displayConfig(true);
      }
      
      private function openTemplatePanel(event:MouseEvent):void
      {
        var config:Object=getConfig();
        var popup:TemplateView = PopUpManager.createPopUp(root, TemplateView, true) as TemplateView;
        popup.addEventListener(TemplateView.TEMPLATE_LOAD, onTemplateLoad)
        popup.config=config;
        PopUpManager.centerPopUp(popup);
      }
    ]]>
  </fx:Script>
  
</actionbar:ActionBar>