[xray-connector] Extract inline script block and event handlers in com/xpandit/plugins/xrayjenkins/task/XrayImportBuilder/config.jelly

This issue is archived. You can view it, but you can't modify it. Learn more

XMLWordPrintable

      Problems

      == Inline Script Block
      Line: 105
      ----
      <script id="_${descriptor.defaultBuildID()}">
              (function(Q){
      
                  var mainTemplate = '';
                  var formats;
      
                  if('${instance.defaultFormats()}' != ''){
                      formats = [${instance.defaultFormats()}];
                  }
                  else{
                      formats = [${descriptor.defaultFormats()}];
                  }
      
                  formats = formats[0];
      
                  addXrayFields_${descriptor.defaultBuildID()} = function(){
      
                      var selectedFormat;
                      if(arguments.length > 0)
                          selectedFormat = formats[arguments[0]];
                      else
                          selectedFormat = formats[Object.keys(formats)[0]];
      
                      //Three steps: fetch template, compile it, generate result with the context data
                      var template = Handlebars.compile(mainTemplate);
                      var result = template(selectedFormat);
                      Q('#configurableFields_${descriptor.defaultBuildID()}').html(result);
      
                      switcherInfoLastConfiguration_${descriptor.defaultBuildID()}();
                      switcherTestInfoLastConfiguration_${descriptor.defaultBuildID()}();
                  }
      
                  /*
                   * Switches the HTML element for the importInfo field
                   */
                  switchInput_${descriptor.defaultBuildID()} = function(container){
      
                      //current selected input type, from the select HTML element
                      var selectedInputType = Q("#selectInputType_${descriptor.defaultBuildID()}").find('option:selected').val();
      
                      if(!selectedInputType){
                          console.error("Couldn't find Test Execution fields selected option element");
                          return;
                      }
      
                      var key = Q("#selectFormat_${descriptor.defaultBuildID()}").find('option:selected').val();
      
                      //selected input type, from last configuration
                      var lastSwitcherConfig = '${instance.getInputInfoSwitcher()}';
      
                      //field to render
                      var _field = (formats[key]).configurableFields.filter(function(field){return field.key == 'importInfo'})[0];
                      _field = JSON.parse(JSON.stringify(_field));
      
                      var renderConfiguration = (lastSwitcherConfig == selectedInputType);
      
                      if(!renderConfiguration)
                          _field.configuration = '';
      
                      if(selectedInputType == 'filePath'){// content is a file path
                          var template = Handlebars.compile('${addInput}');
                          var result = template(_field);
                          Q(container).html(result);
                      }
                      else if(selectedInputType == 'fileContent'){ // content is in JSON format
                          var template = Handlebars.compile('${addTextarea}');
                          var result = template(_field);
                          Q(container).html(result);
                      }
      
                  }
      
                  switchTestInfoInput_${descriptor.defaultBuildID()} = function (container) {
                  	//current selected input type, from the select HTML element
                  	var selectTestInfoInputType = Q("#selectTestInfoInputType_${descriptor.defaultBuildID()}").find('option:selected').val();
      
                  	if(!selectTestInfoInputType){
                  	    console.error("Couldn't find Test Info selected option element");
                  	    return;
                  	}
      
                  	var key = Q("#selectFormat_${descriptor.defaultBuildID()}").find('option:selected').val();
      
                  	//selected input type, from last configuration
                  	var lastSwitcherConfig = '${instance.getInputTestInfoSwitcher()}';
      
                  	//field to render
                  	var _field = (formats[key]).configurableFields.filter(function (field) {
                  		return field.key == 'testImportInfo'
                  	})[0];
                  	_field = JSON.parse(JSON.stringify(_field));
      
                  	var renderConfiguration = (lastSwitcherConfig === selectTestInfoInputType);
      
                  	if (!renderConfiguration){
                  		_field.configuration = '';
                  	}
      
                  	if (selectTestInfoInputType === 'filePath') {// content is a file path
                  		var template = Handlebars.compile('${addInput}');
                  		var result = template(_field);
                  		Q(container).html(result);
                  	} else if (selectTestInfoInputType == 'fileContent') { // content is in JSON format
                  		var template = Handlebars.compile('${addTextarea}');
                  		var result = template(_field);
                  		Q(container).html(result);
                  	}
      
                  }
      
                  switcherInfoLastConfiguration_${descriptor.defaultBuildID()} = function(){
                      //selected input type, from last configuration
                      var lastSwitcherConfig = '${instance.getInputInfoSwitcher()}';
      
                      if(lastSwitcherConfig !== '' ){//making sure the switcher gets the last configuration value
                          var select = Q("#selectInputType_${descriptor.defaultBuildID()}");
                          if(select){
                              select.val(lastSwitcherConfig);
                              select.trigger('change');
                          }
                      }
                  }
      
                  switcherTestInfoLastConfiguration_${descriptor.defaultBuildID()} = function(){
                	    //selected input type, from last configuration
                	    var lastSwitcherConfig = '${instance.getInputTestInfoSwitcher()}';
      
                	    if(lastSwitcherConfig){//making sure the switcher gets the last configuration value
                	    	var select = Q("#selectTestInfoInputType_${descriptor.defaultBuildID()}");
                	    	if(select.length > 0){
                	    		select.val(lastSwitcherConfig);
                	    		select.trigger('change');
                	    	}
                	    }
                  }
      
                  setDocLink_${descriptor.defaultBuildID()} = function(link){
                      Q('#xray-doc-link_${descriptor.defaultBuildID()}').attr('href', link);
                  };
      
                  changeDocLink_${descriptor.defaultBuildID()} = function(){
                      var instanceId = Q('#selectInstance_${descriptor.defaultBuildID()}')[0].value;
      
                      if(instanceId.startsWith('${descriptor.getCloudHostingTypeName()}')) {
                          setDocLink_${descriptor.defaultBuildID()}('${descriptor.getCloudDocUrl()}');
                      } else{
                          setDocLink_${descriptor.defaultBuildID()}('${descriptor.getServerDocUrl()}');
                      }
      
                  };
      
                  filterFormats_${descriptor.defaultBuildID()} = function(){
                      var instanceId = Q('#selectInstance_${descriptor.defaultBuildID()}')[0].value;
                      var cloudExclusiveEndpoints = JSON.parse('${descriptor.getExclusiveCloudEndpoints()}');
                      var serverExclusiveEndpoints = JSON.parse('${descriptor.getExclusiveServerEndpoints()}');
                      var selectedInstanceIsServer = instanceId.startsWith('${descriptor.getServerHostingTypeName()}');
                      var selectedFormat = Q('#selectFormat_${descriptor.defaultBuildID()} option:selected').val();
      
                      Q('#selectFormat_${descriptor.defaultBuildID()} option').prop("disabled", false);
                      if (selectedInstanceIsServer) {
                          for (var index in cloudExclusiveEndpoints){
                              Q('#selectFormat_${descriptor.defaultBuildID()} option[value="'+ cloudExclusiveEndpoints[index] +'"]')
                                      .prop("disabled", true);
                          }
      
                          if(cloudExclusiveEndpoints.hasOwnProperty(selectedFormat)){
                              // if "Server" is selected and the current selected format is a cloudExclusive, then we reset to the sdefault (first) option.
                              Q('#selectFormat_${descriptor.defaultBuildID()}').val("");
                              addXrayFields_${descriptor.defaultBuildID()}("");
                          }
                      } else {
                          for (var index in serverExclusiveEndpoints){
                              Q('#selectFormat_${descriptor.defaultBuildID()} option[value="'+ serverExclusiveEndpoints[index] +'"]')
                                      .prop("disabled", true);
                          }
      
                          if(serverExclusiveEndpoints.hasOwnProperty(selectedFormat)){
                              // if "Cloud" is selected and the current selected format is a serverExclusive, then we reset to the default (first) option.
                              Q('#selectFormat_${descriptor.defaultBuildID()}').val("");
                              addXrayFields_${descriptor.defaultBuildID()}("");
                          }
                      }
                  };
      
                  toggleCredentials = function (ele) {
                      var isUserAuthJiraInstance = ele.find('#selectInstance_${descriptor.defaultBuildID()}')
                                                                             .find('option:selected')
                                                                             .text()
                                                                             .indexOf("[User Auth required] ") === 0;
      
                      const $selectParent = ele
                                  .parent()
                                  .find('#credentialId_${descriptor.defaultBuildID()}')
                                  .parent()
                                  .parent();
                                  
                      if (isUserAuthJiraInstance) {
                          $selectParent.show();
                      } else {
                          $selectParent.hide();
                      }
                  };
      
                  Q(document).ready(function() {
                      // Main template loading. It's syntax conflicts with Jelly so we need to load it asynchronously from an external source
                      Q.ajax({
                          url: '${resURL}/plugin/xray-connector/xray-import-buildstepconfig.html',
                          cache: false,
                          dataType: "html",
                          success: function(data) {
                              mainTemplate = data;
      				        registerHelpers(Handlebars);
                              //Register partial templates, used for call templates inside templates
                              Handlebars.registerPartial("addInputEntry",'${addInputEntry}');
                              Handlebars.registerPartial("addInput",'${addInput}');
      
                              Handlebars.registerPartial("addTextareaEntry",'${addTextareaEntry}');
                              Handlebars.registerPartial("addTextarea", '${addTextarea}');
      
      				        Handlebars.registerPartial("addSameExecutionCheckboxEntry",'${addSameExecutionCheckboxEntry}');
      				        Handlebars.registerPartial("addImportInParallelCheckboxEntry",'${addImportInParallelCheckboxEntry}');
                              Handlebars.registerPartial("addSameExecutionCheckboxEntry",'${addSameExecutionCheckboxEntry}');
      
                              Handlebars.registerPartial("addSwitchableField", '${addSwitchableField}');
      
                              Handlebars.registerPartial("addSwitchableTestField", '${addSwitchableTestField}');
      
                              //get last chosen format
                              var formatSuffix = '${instance.getFormatSuffix()}';
      
                              //if no format was chosen, select the first one from the formats/endpoints list
                              if(!formatSuffix) {
                                  addXrayFields_${descriptor.defaultBuildID()}();
                              }else {
                                  addXrayFields_${descriptor.defaultBuildID()}(formatSuffix); //making sure that the select gets the last configuration value
                              }
      
                              changeDocLink_${descriptor.defaultBuildID()}();
      
                              //register event-handler
                              Q('#selectInstance_${descriptor.defaultBuildID()}').on('change',function(e){
                                  //whenever we select an instance we need to filter the format options and change the doc link
                                  filterFormats_${descriptor.defaultBuildID()}();
                                  changeDocLink_${descriptor.defaultBuildID()}();
                              });
      
                              Q('#selectFormat_${descriptor.defaultBuildID()}').on('change',function(e){
                                  //whenever we select a format we need to render its specific fields
                                  addXrayFields_${descriptor.defaultBuildID()}(e.currentTarget.options[e.currentTarget.selectedIndex].value);
                              });
      
                              Q('#selectFormat_${descriptor.defaultBuildID()}').on('filled', function(){
                                  //when ListBoxModel gets filled, we need to filter the format options
                                  filterFormats_${descriptor.defaultBuildID()}();
                              });
      
                          }
                      });
      
                  });
      
                  setTimeout(function() {
                      changeDocLink_${descriptor.defaultBuildID()}();
                      
                      Q(".xray-import-results-wrapper").each(function () {
                          const wrapperID = Q(this).attr("id");
                          Q(this).removeClass("xray-import-results-wrapper");
                          var ele = Q(Q("#" + wrapperID)
                              .parents('.xray-import-results')
                              .get(0));
                      
                          toggleCredentials(ele);
                          ele.find("#selectInstance_${descriptor.defaultBuildID()}")
                              .change(function () {
                                  toggleCredentials(ele);
                              });
                              
                          setTimeout(function() {
                              toggleCredentials(ele);
                          }, 1000);
                      });
                                          
                  }, 500);
              })(jQuery);
      
          </script>
      ----
      
      == Inline Event Handler
      Line: 52
      ----
      <select name="_.inputInfoSwitcher" class="setting-input" id="selectInputType_${descriptor.defaultBuildID()}" onchange='switchInput_${descriptor.defaultBuildID()}("#switchContainer_${descriptor.defaultBuildID()}")'>
      ----
      
      == Inline Event Handler
      Line: 67
      ----
      <select name="_.inputTestInfoSwitcher" class="setting-input"
          				id="selectTestInfoInputType_${descriptor.defaultBuildID()}"
          				onchange='switchTestInfoInput_${descriptor.defaultBuildID()}("#switchTestInfoContainer_${descriptor.defaultBuildID()}")'>
      ----
      

      Solutions

      https://www.jenkins.io/doc/developer/security/csp/#inline-javascript-blocks
      https://www.jenkins.io/doc/developer/security/csp/#inline-event-handlers

            Assignee:
            Unassigned
            Reporter:
            Basil Crow
            Archiver:
            Jenkins Service Account

              Created:
              Updated:
              Archived: